Hello,
When creating a new mapped object to be persisted with hibernate, I usually need to set its mapped members too (nullable=false).
These members might exist in the database and have a lot of properties of their own.
I want to avoid fetching all of the data of its members. Actually, I want to avoid fetching any of the members completely (JDBC equivalent would be just to INSERT INTO with the right values as fk to member tables).
However, when creating my new Java Object I must set its mapped members too, to create these I have to find in the database first, resulting with redundant hits to the DB.
I am using the following solution:
I create the members of my "new" Java object with the "new" keyword (transient and not persistent, although the same object exist in the DB) and I set only the necessary values (e.g., its pk) then I set these members to my new object.
Code:
NewCreatedObject myNewCreatedObject = new NewCreatedObject ();
ExistingMemberObject existingMemberObject = new ExistingMemberObject (); //exist in the DB
existingMemberObject.setPk(3); //Not setting "description,creationdate,etc..."
myNewCreatedObject .setExistingMemberObject (existingMemberObject);
save(myNewCreatedObject);
It works fine so far, but I have a couple of questions :
A) Is that the way to do that?
B) I also want to be aware if the member I've just created not exists in the DB. how can I get this indication without finding that object and without trying to persist the new created member object? (JDBC equivalent is Integrity constraint violation)
Thanks