Hiberate persistent objects

 First, the requirements of persistent classes

1. Provide a parameterless constructor, the modifier is at least visible to the package, Hibernate can use Constructor.newInstance() to create persistent classes;

2. Provide an identification attribute, which is usually used to map the primary key field of the database table (the identification attribute may not be provided, but this is not recommended);

3. Provide get and set methods for all properties of persistent classes;

4. Use non-final classes (if the persistent class does not implement any interface, Hibernate uses CGLIB to generate the proxy, if the final class is used, CGLIB cannot be used), and similarly, avoid declaring public final methods in non-final classes;

5. Rewrite the equals and hashCode methods (which can be implemented by comparing the values ​​of two object identifiers, but this method cannot be used for objects that use automatically generated identifiers), usually using equal business key values ​​to implement equals() and hashCode( );

 

Second, the state of the persistent class



 When a Session calls the close() and clear() methods, all instances associated with the Session will be affected

 

3. Methods of changing the state of persistent objects (some introductions)

1. The difference between save() and persist()

The save() method will return the identity attribute value (ie the primary key value) of the persistent object, the persist() method will not

Executing the save() method will immediately insert the persistent object into the database, and persist() ensures that when it is called outside a transaction, it is not immediately converted to an insert statement

2. The difference between load() and get()

The main difference is whether to lazy load or not.

When the get() method is executed, the database will be accessed immediately, and if there is no data, null will be returned;

When the load() method is executed, the database will not be accessed immediately. If the object trying to load does not exist, an uninitialized proxy object will be returned;

Changes made by the program to persistent objects are automatically saved to the database before the session flush.

3. The difference between merge() and update()

Execute the update() method, the persistent object of the managed state will become the persistent state;

When the merge() method is executed, the persistent object of the managed state will not become a persistent state;

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326897155&siteId=291194637