This week's book giveaway is in the Java in General forum.
We're giving away four copies of Beginning Java 17 Fundamentals: Object-Oriented Programming in Java 17 and have ishori Sharan & Adam L Davis on-line!
See this thread for details.
Win a copy of Beginning Java 17 Fundamentals: Object-Oriented Programming in Java 17 this week in the Java in General forum!

Nico van de Kamp

Ranch Hand
+ Follow
since Jan 25, 2017
Cows and Likes
Cows
Total received
1
In last 30 days
0
Total given
0
Likes
Total received
0
Received in last 30 days
0
Total given
0
Given in last 30 days
0
Forums and Threads
Scavenger Hunt
expand Ranch Hand Scavenger Hunt
expand Greenhorn Scavenger Hunt

Recent posts by Nico van de Kamp

I have made a CRUD as most tutorials. This was working in my opinion good. The database data was manupulated, records added, deleted etc.

My code is refactored and the add record, update record, a 'refresh' is added, with a 'special' repository..., which I do not understand.

Here is the special repository:

Here is my refactored add record method with the refresh call and the colleague note:


I think and expect, that if everything is well coded, the save is updating the database and the persistence context as well, or..?.
I expect that this is default implemented by Hibernate or...?
(I have asked my colleague who refactored it a few weeks ago on the teams chat. The answer was it is hard to explain in a few words and takes to long... And honestly is must say I have not asked it again)

But now I must do an investigations about CQRS, because the idea was to use this instead of CRUD  for a relative simple app.

With this investigation I came across this webpage:


This is a refresh used to update a materialized view, which I understand if the refresh is therefore used.
I have test it, and if I execute a new order than the materialized view is updated with totals as well.

My question at the end is, with a simple/normal- straight CRUD - save via the repository, is it required to execute a refresh for update persistence layer?
And are there maybe special cases when you should do that?
1 week ago

Tim Holloway wrote:Forgive my blindness, but I can't find the explanation of what "N+1" error means.



You're blindness? I have noticed that you know a lot more than I do about this. So I must be very thankful to you and Rob.
But what my colleague suggest and I mean is https://www.vincenzoracca.com/en/blog/framework/jpa/jpa-fetch/]this and/or this this

Tim Holloway wrote:I do this all the time. In fact, I keep 2 distinct persistence logic layers in most of my apps. The lower-level (DAO) layer handles table-level stuff, the higher-level (service) layer handles the whole group of records as a working set.


This is hard to understand for me or to visualize it what you exactly mean byt this. I know so far DAO = Data Access Object layer, I'm working with a service layer and a DTO. But what or why do you split up?
Or do you mean entity for the table stuff and of course the service layer for handling the records?

Tim Holloway wrote:If you're seeing tons of SQL operations when doing something like this, then chances are that you're either not relating the Entity objects properly or your queries are not properly formed.


This is for sure! I had first solved it with JPQL. I found it on Baeldung. But my colleague has refactored it, this was not the way to go we need to solve it with JPA. But that doesn't perform due that we have not properly formed our model with JPA. So I have add the JPQL again, at least it is performing now from 12 seconds to 18 ms!

But I will try to find out if also will work with JPA/Hibernate.
1 week ago

Tim Holloway wrote:I think that before you go too far down that road you should look at Apache Lucene. It's designed to support text searches on databases.



I was going in the wrong direction. This is way if you want to solve this with JPA/Hibernate I think.

I have found my solution like this:
In My 'applySearchPredicate' method I can add so much predicates as I want.  This was an 'emergengy' case - Log4J -, they should like to search through the remarks table on different words instead off exact string.
Ok, I have prepared it, but nothing heard it anymore, so it was not necessary to implement it. BUT now know how I can solve it. If this is the right solution?
1 week ago
Hello,

I'm trying to define a specification for a JPQL. I'm using JPQL because If I use JPA like "findByNaamContainingIgnoreCaseOrOmschrijvingContainingIgnoreCase(...)", than I have the N+1 issue.
Here is my JPQL query, which is working fine for me:

The search is now working based on the exact word or string. Now comes the question to search on 1 or more words divide by space. For example: "This is an Demo", than I want divide the string by spaces and that the search will be done on every single word and every demo which have one of these words - 'This', 'is', 'an', 'Demo' - will be returned.

Is it possible that I don't need to add OR statements lines but just add a specification\JpaSpecificationExecutor?

Repository:


DemoSearchCriteria:

I try now to figure out how I define the DemoSpecification to add different words for the multiple column with null or more search key words, so that I can use these in my JPQL.
Or is this not possible?


Here is my Specification for the search with concrete value's on operations as GREATER_THAN or LESS_THAN.
1 month ago

Tim Holloway wrote:One of the major strengths of JPA is that you don't normally have to code JOINs in JPQL. Instead you code the entity relationships (OneToMany, ManyToOne, OneToOne, ManyToMany) as annotations of the Entity class definitions and let JPA handle the joining.

You have a lot of code there and it's early in the morning, but I suspect that if you leveraged JPA properly you'd have a lot less code and it would be easier to understand.




I have moved from JPA (findByNaamContainingIgnoreCaseOrOmschrijvingContainingIgnoreCase) to JPQL, because of the N+1 issue.

On the project were I'm working on, there are 4 tables, the main table has 800 records, logging table 2400 records and two tables with static data, which mean nothing in my opinion.

But to open to frontend for a list of records takes nearly 12 seconds!!! I saw in de console log that for every single record al the subrecords would be retrieved in separated querys, instead of just 1 query, I believe a kind of 2800 query's were executed.
So I moved to JPQL and now it is one query and take 24 - 18 ms, ok also with less data I understand.

Tim Holloway wrote:
That CriteriaBuilder especially bothers me because I suspect that all those constant parameters should be in an array of Strings and fed in via a simple query. CriteriaBuilder is primarily for when you want to make query components optional.



If I understand this, I have a question about this with specification and JpaSpecificationExecutor.
1 month ago
Hi Rob,

Thanks. I was already experimenting with it and  was trying this:

But I was also different things trying and I removed . I have put it back it is working now.

The only thing I detected now is that, if I add , that the constructor in the DemoEntity is missing this field. So I need to find out this, but I will do this tommorow.
1 month ago
Hello,

I try to figure out how to to make a join with subtable.

Here my SQL script in short, which is making clear I hope what I want:
I have made a JPQL which working for the demoEntity.
This is working without the join line. If I do a request with postman al the demo records are returned than.

But with adding the join line than I get the error message: "...InvalidDataAccessApiUsageException: Unable to locate Attribute  with the the given name [demo_id] on this ManagedType..."

Here is the demoEntity and loggingEntity relation:On the logging Entity I had nothing defined (unidirectional), but that field "demo_id" is defined/exist in the database.
So I thought JPQL is maybe this property expecting in the LoggingEntity so I have defined this property but I get still the same error message:


--

Than the next step is than to extend the search opportunity

I will continu to search the internet, but if someone has an idea how to solve this would be very helpfull.
1 month ago
Hello,

Last week I succeeded to solve this...


This JPA query is returning the result which first sorted on the teamnaam and inside this sorting on the businessUnitNaam
1 month ago
Hello,

I have two entities which do have a relation @ManyToOne - Entity one with Entity two. I want order first on the parent entity and than inside this result order on Entity two;
In SQL it is this:


Ordening for entity 1 is not difficult with JPA by adding the next line in the entity 1 repository interface:

But then ordening on entity 2 how is that possible with JPA? I try to add to order on entity 2 on different ways something like:

This doesn't work.

What I see in the console log about ordening is:
...
order by
    entity1entity0_.name asc
    entity1entity0_.entity2_id asc
...
I do not understand why it is ordening on the fk? I'm not aware that I have defined this anywere.

Is this anyway possible in JPA? Or do I have to go to JPQL, HQL or something like that?

Nico
1 month ago
I try to make myself 'comfortable' with the Java eco-system as JPA and Hibernate.

I have for instance made a class employee with sequence:


I can CRUD records with Postman is working perfectly.

But now I have inserted records with SQL (INSERT INTO table name ()).
Now I try to insert a record with postman, I get the error message: rg.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: Unique index or primary key violation: "PRIMARY KEY ON PUBLIC.ADDRESS(ID) [1, 'town name', '0', 'street name']"; SQL statement:

I think that's due that I add records by SQL statements. Hibernate 'thinks'  the sequence is still one and I can imagine that it goes wrong.

In the 'real (=production)' environment, what is than the best way to implement this?
Defining the complete schema with Liquibase/flyaway for example and simply define sequence as:

And are there some more 'little' things where I need to have tobe where off?
3 months ago
I try to learn JPA/Hibernate and last week I had a remarkable error:

"status": 500,
"error": "Internal Server Error",
"trace": "org.springframework.http.converter.HttpMessageConversionException:
Type definition error: [simple type, class com.crud.demo.dto.EmployeeDto];
nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException:
No serializer found for class com.crud.demo.dto.EmployeeDto and no properties discovered
to create BeanSerializer



In my DTO I had only setters implemented, because if need getters than I thought I will do this from the Entity ==> the unique source.

After some hours I added in my DTO classes the getters and the getter for the id was immediately syntax highlighted --> collaring which means it is used. So Im searching where? And IntelliJ 'Find usage' I get the message "Usages or base methods of getId() Nothing found in 'All Places'"


Is that not strange? At least it is now working but I don't understand it...

3 months ago
I did get it working a few weeks ago only I have changed Unit with Roles.

Employee Entity is my 'Parent' side


And Role is my 'child' side:


Join table is employees_roles. If I remove a role from my REST Api, than also an record of the join table is removed and not from the Role table!! That's good because the Role table is an constant/lookup table.

The only question what is left is that:
My Role table has three fields: id, code and description
It is constant/lookup table with 6 prefilled records.
Question: if I change the value of the field "description" and/or code, than it is overwritten. How can I disable this, so that only records in join table are added?

** EDIT **

Ah, I read also my other post and I think Rob has given the solution there.
The solution I assume is 'insertable = false, updatable = false':

It seems strange to me if this is the 'real' solution because how do you maintain this table? Than you have to write another class...? I should expect that you disable it from the parent side writing to the child table.

If somebody does have another idea and/or better idea, let me know.
3 months ago
Hello,

I'm still struggling and fighting to get a OneToMany/ManyToOne working. The examples I have found till now, have the same issue and I have also found here the question but not the solution or I do not understand it.

I have the two Entities:
parent Employee @OneToMany:The Child side: @Many-To-One:

The update employee service implementation:

And this is what I inject with Postman the create (POST):

I have two "employeeModelLogging" records at the time of creation of an Employee.

Now I do an update with postman:

When I execute the update, than there are still two records in the database. (It is not a problem to update fields from the employee or department, etc. This is working fine)

I have tried this, by removing the second recordThe second loggingModel is removed from the JPA I think, but not in the database. But I this, if this should work, than at least I know which way I have to go...

I hope that someone has an idea and can tell me what I'm doing wrong...
Hi Rob,

Thanks for you're help,

Rob Spoor wrote:I take it that the model classes are mapped from JSON directly to your entities, right? If so, you're running into a bidirectional relation that is only set on one side. The unmarshalling from JSON creates new LoggingModel instances, and puts them into a list. It then sets that list on the created EmployeeModel instance. The EmployeeModel instance now has a reference to all of its LoggingModel instances. What is still missing is the reference in the LoggingModel instances to the EmployeeModel instance. The JSON unmarshalling doesn't set this because it simply doesn't know it should.

A quick solution is to fix these references yourself. A quick for-each statement will suffice:



Although I do not know what 'unmarshalling' exactly means, it is all right what you here suggest!!!

But I'm AMAZED that what you suggest here works!!!.

I've changed the code into this: So I add you're line just before saving the new employee model. What is amazing me, is that the id of employee is still unknown because the Employee is not saved or...,
Does it work in this way: JPA knows the next id sequence number for the Employee Entity. So this number is retrieved from the JPA and saved as FK for the loggingModel. Is this what is happening?








I have two entities:

I understand the problem. The FK (name: LOGGINGEMPLOYEEMODEL_ID ) is in the tabel "loggingmodel".
At the moment of new record saving for the parent table 'employeedetails' the child table should also be updated.  But I get the error: "org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: NULL not allowed for column "LOGGINGEMPLOYEEMODEL_ID"; SQL statement:
insert into LoggingModel (infotext, loggingEmployeeModel_id, title, id) values (?, ?, ?, ?) [23502-199]"

I understand it, the new id for the employeedetails is unknown for the FK for child table. (If it take the part "employeeModelLogging" out of the Postman injection, than I don't get the constraint error, so it should the loggingModel part)

How do I solve this within JPA - Hibernate?

The parent side: One-To-Many:

The Child side: Many-To-One:


The create employee service implementation:

And this is what I inject with Postman:

Can someone can give an idea/hint what I'm doing wrong?