In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "the content essentials of Hibernate configuration". In the daily operation, I believe many people have doubts about the content points of Hibernate configuration. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "content essentials of Hibernate configuration". Next, please follow the editor to study!
1. Two profiles:
A.hibernate.cfg.xml and B.hibernate.properties
The configuration of the mapping file can be included in A, and the mapping file can be added to hard codes in B.
A.Configuration config=new Configuration () .config ()
B.Configuration config=new Configuration ()
Config.addClass (TUser.class)
two。 You don't have to use the file name hibernate.cfg.xml or hibernate.properties, and you don't have to put the configuration file under Classes.
File file=new File ("c://sample//myhibernate.xml"); Configuration config=new Configuration (). Config (file)
3. Session.Flush () forces the database to synchronize immediately. When using a transaction, there is no need to use flush. Transaction commit automatically calls flush and flush is also called when session is closed.
4. Hibernate always uses the object type as the field type
5. XDoclet specially established hibernate doclet, that is, add some java docTag to the java code, and then let XDoclet analyze the java code to generate a mapping file.
The 6.HQL clause itself is case-insensitive, but the class and attribute names that appear in it must be case-sensitive.
7. Relationship: Constrained: constraint, indicating whether there is a foreign key (foreigh key) on the primary key of the master table to constrain it.
Property-ref: the attribute name used to associate with the master class in the associated class, which defaults to the primary key attribute name of the associated class
One-way one-to-many needs to be configured on one side, and two-way one-to-many on both sides.
8.lazy=false: the passive party's record is memorized by hibernate and then stored in the Collection type attribute specified by the master.
9. Collection of type java.util.Set or net.sof.hibernate.collecton.Bag
10. Important: inverse: used to identify one end of the passive party in a two-way association.
One party (the master) of the inverse=false is responsible for maintaining the relationship. Default value: false
11.batch-size: when using the delayed loading feature, the number of data read at a time was yesterday.
twelve。 One-to-many updates through the master (when the master is a party)
User.getAddresses () .add (addr); session.save (user); / / cascading update through master object
13. In the one-to-many relationship, setting the many as the active party (inverse=false) will help improve the performance. When one party sets up a relationship, inverse=true will hand over the control to multiple parties, so that many parties can take the initiative to obtain foreign key from one party, and then an insert can be completed.
Addr.setUser (user); / / sets the associated TUser object user.getAddresses () .add (addr); session.save (user); / / cascading updates
14. Only the party who is set as the main prosecution cares about the attributes of the other party, and the passive party does not care about the attributes of the other party.
The configuration properties of 15.one-to-many and many-to-one nodes are different:
The one-to-many relationship has two attributes, lazy and inverse, many-to-many node attributes:
Column: the associated field of the associated target table in the intermediate mapping table
Class: class name, associated target class
Outer-join: whether to use outer join or not
Note: access is the way to set property values.
Column is the setting associated field.
16. Many-to-many. Note that inverse and lazy,cascade can only be set to insert-update on both sides.
In a many-to-many relationship, because two tables refer to each other, the state of the relationship must be saved to both parties at the same time.
Group1.getRoles (). Add (role1); role1.getGroups (). Add (group1); session.save (role1); session.save (group1)
17. About vo and po
After hibernate capacity processing, the vo becomes po (the reference to the vo will be saved by the container and flush when the session is closed, so it is dangerous if the po is passed to other places to change.) vo and po convert to each other: BeanUtils.copyProperties (anotherUser,user)
18. For save operations, no specific operation is required if the object is already associated with the Session (that is, it has been added to the entity container of the Session). Because later in the Session.flush process, Hibernate will traverse the objects in this entity container, find out the changed entities, generate and execute the corresponding update statements.
19. If we use the deferred loading mechanism, but want to achieve the function of non-deferred loading in some cases, that is, we hope that after Session is closed, the addresses property Hibernate.initialize method that still allows manipulation of user can do this by forcibly loading associated objects: that's why when we write POJO The reason for the Collection attribute must be declared with a JDK Collection interface (such as Set,Map), rather than a specific JDK Collection implementation class (such as HashSet, HashMap).
20. Transaction: the autocommit property of the session obtained from sessionFactory has been turned off (AutoCommit=false). If the jdbc operation is performed, the transaction operation will not be performed if session.BeginTransaction () is not explicitly called.
Jdbc transaction: transactions based on the same session (that is, the same connection)
Jta transaction: cross-session (cross-connection) transactions.
There are three ways to implement jta transactions:
A 、
UserTransaction tx=new InitialContext (). Lookup ("..."); tx.commit ()
B. the method of using hibernate encapsulation: (not recommended)
Transaction tx=session.beginTransaction (); tx.commit ()
C. Using the transaction technology of ejb's sessionBean, you only need to declare the methods that require jta transactions as require in the release descriptor.
21. Pessimistic lock, optimistic lock:
Optimistic locking is generally achieved through version, so note that the version node must appear after the id.
In 22.Hibernate, you can set the paging range through the Criteria.setFirstResult and Criteria.setFetchSize methods.
A consistent method is also provided in the Query interface, and hibernate is mainly implemented in this function in the dialect class.
23.
Cache... Net.sf.ehcache.hibernate.Provider
You also need to configure ecache itself.
Then specify the cache policy of each mapping entity in the mapping file
....
* * *
Query.list () is different from Query.iterate (): for query.list (), you always get all records through a sql statement, then read them out and fill them in pojo to return; but query.iterate () first gets the id of all records that meet the query criteria through a Select SQL, and then loops through the id collection, fetching the records corresponding to each id through a separate Select SQL, and then filling it into POJO to return.
That is, for the list operation, a SQL is required to complete. For iterate operations, 1 SQL is required. The list method will not read data from the Cache. Iterator would.
24.ThreadLocal: it maintains a private variable space for each thread. In fact, the implementation principle is to maintain a Map in JVM, the key of this Map is the current thread object, and the value is the object instance saved by the thread through the ThreadLocal.set method. When a thread calls the ThreadLocal.get method, ThreadLocal will fetch the corresponding object in the Map and return based on the reference of the current thread object.
In this way, ThreadLocal isolates variables from different threads by distinguishing them by references to individual thread objects.
Examples of 25.Hibernate official development manual standards:
Public class HibernateUtil {private static SessionFactory sessionFactory; static {try {/ / Create the SessionFactory sessionFactory = new Configuration (). Configure (). BuildSessionFactory ();} catch (HibernateException ex) {throw new RuntimeException ("Configuration problem:" + ex.getMessage (), ex);}} public static final ThreadLocal session = new ThreadLocal (); public static Session currentSession () throws HibernateException {Session s = (Session) session.get () / / Open a new Session, if this Thread has none yet if (s = = null) {s = sessionFactory.openSession (); session.set (s);} return s;} public static void closeSession () throws HibernateException {Session s = (Session) session.get (); session.set (null); if (s! = null) s.close ();}}
twenty-six。 Reuse of session through filter:
Public class PersistenceFilter implements Filter {protected static ThreadLocal hibernateHolder = new ThreadLocal (); public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {hibernateHolder.set (getSession ()); try {. Chain.doFilter (request, response); } finally {Session sess = (Session) hibernateHolder.get (); if (sess! = null) {hibernateHolder.set (null); try {sess.close ();} catch (HibernateException ex) {throw new ServletException (ex);}. }
The parameterized transaction management function of 27.Spring is quite powerful. The author suggests that container-managed transactions should be used as much as possible in Spring Framework-based application development to obtain the readability of data logic codes.
Public class UserDAO extends HibernateDaoSupport implements IUserDAO {public void insertUser (User user) {getHibernateTemplate () .saveOrUpdate (user);}}
The above UserDAO implements a custom IUserDAO interface and extends the abstract class:
HibernateDaoSupport HibernateSupport implements the association between HibernateTemplate and SessionFactory instances.
HibernateTemplate encapsulates the Hibernate Session operation, and the HibernateTemplate.execute method is the core of an encapsulation mechanism.
* in the configuration file of spring, the contents of the entire hibernate.cfg.xml are migrated.
At this point, the study on the "content points of Hibernate configuration" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.