Hibernate configuration points

Source: Internet
Author: User

1. Two configuration files:

A. hibernate. cfg. xml and B. hibernate. properties

A can contain the configuration of the ing file, while hard codes in B adds the ing file.

A. Configuration config = new Configuration (). config ();

B. Configuration config = new Configuration ();

Config. addClass (TUser. class );

2. You do not have to use the hibernate. cfg. xml or hibernate. properties file names. You do not have to put the configuration file under Classes,

 
 
  1. File file=new File("c://sample//myhibernate.xml");  
  2. Configuration config=new Configuration().config(file);  

3. session. Flush () forces the database to synchronize immediately. When a transaction is used, it does not need to be flush. The transaction commit will automatically call flush when the session is closed.

4. Hibernate always uses the object type as the Field Type

5. XDoclet specifically sets up hibernate doclet, that is, adding some java docTag to the java code, and then letting XDoclet analyze the java code to generate a ing file;

6. The HQL clause is case-insensitive, but the class name and attribute name must be case sensitive.

7. Relationship: Constrained: constraint, indicating whether a foreign key foreigh key exists in the primary key of the master table.

Property-ref: name of the property associated with the main control class in the association class. The default value is the primary key property name of the association class.

One-to-multiple deployment must be configured on one side, and one-to-multiple deployment must be configured on both sides.

8. lazy = false: the passive records are recorded by hibernate and stored in the Collection type attribute specified by the master.

9. Collection of java. util. Set or net. sof. hibernate. collecton. Bag Type

10. Important: inverse: used to identify the passive end of a bidirectional Association.

Inverse = false) is responsible for maintaining the association. Default Value: false

11. batch-size: the number of data records read at a time when the feature is loaded with latency.

12. When one-to-multiple master vertices are updated through the primary prosecution)

 
 
  1. User. getAddresses (). add (addr); session. save (user); // cascade update through the master object

13. In the one-to-one relationship, setting the active side as inverse = false will help improve the performance. When one party sets the link, inverse = true, that is, the master control is handed over to multiple parties, so that multiple parties can take the initiative to obtain the foreign key from one party, and then one insert can be completed.

 
 
  1. Addr. setUser (user); // sets the associated TUser object
  2. User. getAddresses (). add (addr );
  3. Session. save (user); // cascade update

14. Only the party with the primary prosecution is concerned with the access to the other party's attributes. The passive party does not care about the other party's attributes.

15. The configuration attributes of one-to-one and one-to-one nodes are different:

The one-to-multiple relationship has the following attributes: lazy and inverse:

Column: fields associated with the target table in the intermediate ing table

Class: class Name, associated with the target class

Outer-join: whether to use outer join

Note: access is the read method for setting the attribute value.

Column is the associated field.

16. many to many. Note that both parties must set inverse and lazy. cascade can only be set to insert-update.

In many-to-many relationships, because the association relationship is referenced by two tables, the two tables must be saved simultaneously when the relationship state is saved.

 
 
  1. group1.getRoles().add(role1);  
  2.  
  3. role1.getGroups().add(group1);   
  4.  
  5. session.save(role1);  
  6.  
  7. session.save(group1);  

17. About vo and po

After hibernate capacity processing, vo becomes a po (the reference of this vo will be saved by the container and flush when the session is closed, so if the po is transferred to other places, it is dangerous. vo and po are converted to each other: BeanUtils. copyProperties (anotherUser, user );

18. For the save operation, if the object has been associated with the Session, that is, it is added to the Session object container), no specific operation is required. In the subsequent Session. flush process, Hibernate will traverse the objects in the object container, find the starting and changing objects, generate and execute the corresponding update statement.

19. if we adopt the delayed loading mechanism, but want to implement the non-delayed Loading Function in some cases, that is, after the Session is closed, you can still operate on the addresses attribute Hibernate of the user. the initialize method can implement this function by forcibly loading correlated objects: this is precisely why we must use JDK Collection interfaces such as Set and Map when writing POJO ), the reason for declaring the Collection attribute is not specific to JDK Collection implementation classes such as HashSet and HashMap.

20. transaction: the session is obtained from sessionFactory, and its automatic submission attribute is closed (AutoCommit = false). If the jdbc operation is performed, the session is not explicitly called. beginTransaction () does not execute transaction operations.

Jdbc transaction: A transaction based on the same session (that is, the same connection;

Jta transaction: Cross-session cross-connection) transaction.

There are three implementation methods for jta transactions:

A,

 
 
  1. UserTransaction tx=new InitialContext().lookup("...");   
  2. tx.commit();  

B. hibernate encapsulation method: (not recommended)

 
 
  1. Transaction tx=session.beginTransaction();   
  2. tx.commit();  

C. Use the transaction technology of sessionBean of ejb. You only need to declare the method that requires jta transaction in the release descriptor as require.

21. pessimistic lock, optimistic lock:

Optimistic locks are generally implemented by version. Note that the version node must appear after the id.

22. In Hibernate, you can use the Criteria. setFirstResult and Criteria. setFetchSize methods to set the paging range.

The Query interface also provides the same method. hibernate mainly implements this function in the dialect class.

23.

 
 
  1. cache   
  2. ……   
  3. net.sf.ehcache.hibernate.Provider  

You also need to configure the ecache itself

Then, specify the cache policies for each ing object in the ing file.

....

**************************************** *************

Query. list () and Query. iterate (): For query. list () always obtains all records through an SQL statement, reads them, and fills them in pojo for return; but query. iterate () is to first obtain the IDs of all records that meet the query conditions through a Select SQL statement, and then perform cyclic operations on this id set, use a separate Select SQL statement to retrieve the records corresponding to each id, and then enter the records in POJO to return the results.

That is to say, the list operation requires an SQL statement. For iterate operations, n + 1 SQL statement is required. The list method does not read data from the Cache. But iterator does.

24. ThreadLocal: it maintains a private variable space for each thread. In fact, the implementation principle is to maintain a Map in JVM. The Map key is the current thread object, and the value is the object instance saved by the thread through the ThreadLocal. set Method. When the thread calls the ThreadLocal. get method, ThreadLocal retrieves the corresponding objects in the Map based on the reference of the current thread object.

In this way, ThreadLocal isolates variables of different threads by distinguishing the references of various thread objects.

25. Hibernate Official Development Manual standard example:

 
 
  1. public class HibernateUtil {   
  2. private static SessionFactory sessionFactory;   
  3. static {   
  4. try {  
  5. // Create the SessionFactory sessionFactory =  
  6. new Configuration().configure().buildSessionFactory();  
  7.  } catch (HibernateException ex)  
  8. {  
  9. throw new RuntimeException( "Configuration problem: " + ex.getMessage(), ex );  
  10.  }  
  11.  }  
  12. public static final ThreadLocal session = new ThreadLocal();  
  13. public static Session currentSession() throws HibernateException {  
  14. Session s = (Session) session.get();   
  15. // Open a new Session, if this Thread has none yet if (s == null) {  
  16. s = sessionFactory.openSession(); session.set(s);  
  17. }  
  18. return s;   
  19. }   
  20. public static void closeSession() throws HibernateException  
  21. {  
  22. Session s = (Session) session.get();  
  23. session.set(null);  
  24. if (s != null) s.close();  
  25. }  

26. Reuse session through filter:

 
 
  1. public class PersistenceFilter implements Filter {  
  2. protected static ThreadLocal hibernateHolder = new ThreadLocal();  
  3. public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)  
  4. throws IOException, ServletException{  
  5. hibernateHolder.set(getSession());  
  6. try {  
  7. ……  
  8. chain.doFilter(request, response);  
  9. ……  
  10. }  
  11. finally {  
  12. Session sess = (Session)hibernateHolder.get();  
  13. if (sess != null) {  
  14. hibernateHolder.set(null);  
  15. try {  
  16. sess.close();  
  17. }  
  18. catch (HibernateException ex) {  
  19. throw new ServletException(ex);  
  20. }  
  21. }  
  22. }  
  23. }  
  24. ……  

27. The parameterized transaction management function of Spring is quite powerful. In Spring Framework-based application development, I suggest using containers to manage transactions as much as possible to obtain the optimal readability of Data logic code.

 
 
  1. public class UserDAO extends HibernateDaoSupport implements IUserDAO {  
  2. public void insertUser(User user){  
  3. getHibernateTemplate().saveOrUpdate(user);  
  4. }  

The preceding UserDAO implements the custom IUserDAO interface and extends the abstract class:

HibernateDaoSupport HibernateSupport associates HibernateTemplate with SessionFactory instances.

HibernateTemplate encapsulates Hibernate Session operations, while the HibernateTemplate.exe cute method is the core of an encapsulation mechanism.

* In the spring configuration file, the entire content of hibernate. cfg. xml is transplanted.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.