This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I need some clarification for the text in the documentation. Below is extracted from �Hibernate Reference Documentation Version: 3.1.3� Section 1.2.1 :
[Explaining about the id field of an object/class]� we usually don't manipulate the identity of an object, hence the setter method should be private. Only Hibernate will assign identifiers when an object is saved. You can see that Hibernate can access public, private, and protected accessor methods, as well as (public, private, protected) fields directly. The choice is up to you and you can match it to fit your application design.
[Only Hibernate will assign identifiers when an object is saved.] � Assign identifiers by inserting directly into the DB id field and not assign to the field in the Java object instance ?
[You can see that Hibernate can access public, private, and protected accessor methods, as well as (public, private, protected) fields directly.] � I don�t understand how a hibernate class can access the private methods and fields in my persistence pojo class. I thought NO class outside of a class could access private fields and methods ? Isn�t this the purpose of the keyword �private� ? To prevent outside access ?
To add to Scott's response. You can set the ID generator to be set to "assigne" which means your application logic will define the ID, which means you will need the application code to call setId() which you would then want set to public. But if you want to make sure that your application doesn't do anything nasty like change the Primary Key that is already set in the database. This can cause identity problems and duplicate rows being entered. And even if you were to assign it in code say with the value 10, and you have a Sequence Table which is currently at 5. Then 5 inserts later, using the sequence number would try to insert a new record with ID 10, which already exists and throw an Exception. By keeping the setId() method to private you protect against this.