When a session is obtained by inheriting the hibernatedaosupport class, the following benefits are provided:
If you are not familiar with the session, please first look at the session
1): Because hibernatedaosupport already has the getsession () method for obtaining the session, you can directly use session Se = This. getsession ();. At this time, session is required after the transaction operation is completed. close () or this. releasesession (session); close the session.
Plug-in: hibernate obtains the session in several ways: 1. Session session = sessionfactoryutils. getsession (getsessionfactory (), true); ----> the most basic method for obtaining 2. Session session = new configuration (). Configure (). buildsessionfactory (). opensession ();, ------> obtained through the configuration file
Other configuration usage The configure () method of configuration also supports parameter-based access. You can specify the location of the HBM. xml file instead of using the default classpath. The following hibernate. cfg. xml method, for example: Configuration CFG = new configuration (). Configure ("myexample. xml ");Sessionfactory = new configuration (). buildsessionfactory (); |
3, sessionfactory Sessionfactory = new configuration (). buildsessionfactory (); sessionfactory. opensession (); Sessionfactory. getcurrentsession (); ----> the first dead opensession (), followed by the current session. You can minimize the memory usage. The same as the first one is getcurrentsession (); 4. Session session = This. getsession (); If hibernatedaosupport is inherited. 5. Write a hibernateutils class and open opensession () in it (). For example
A typical transaction shocould use the following idiom: Recommended official statement: Session sess = factory.openSession(); Transaction tx; try { tx = sess.beginTransaction(); //do some work ... tx.commit(); } catch (Exception e) { if (tx!=null) tx.rollback(); throw e;//e.printStackTrace(); } finally { sess.close(); } Interface session extends SESSION (below is a common method in gaisession) extends serializable |
|
@ 1 --> master the usage of several basic methods in the session.
Createquery: queries can only be performed using hql statements. This method and the following createsqlquery can also be updated, such as session. createquery (hql ). Executeupdate (); Load the list with the bean generated by hibernate as the object and return the list set. SQL statement generated when you call. List (): Select userid, username from Tuser; Call session. createquery ("from user U "). the SQL statement generated when iterator () is: Select userid from Tuser; it can be seen that list () reads data from the database at a time and directly fills in the list. Iterator () reads the primary key of the data from the database. It is executed only when the iterator is cyclically added: Purpose: Createsqlquery: You can use an SQL statement to query and store data in an array of objects. session. createsqlquery (SQL). addentity (dtree. Class). List (); you can return the list set. Purpose: Conclusion: The createsqlquery SQL statement query directly queries the table. The execution speed is faster than that of createquery. For createquery, The hql object query requires the hbing file HBM. xml configuration. |
3): Save Method Save method stores an object into the database. The storage method is used to store objects in the database. It's really awkward to translate it. That means it insert an entry if the identifier doesn't exist, else it will throw error. = If the identifier does not exist, it will insert (SAVE) an object. If the identifier already exists, it will throw an error. If the primary key already present in the table, it cannot be inserted. = "If the table already has a primary key, the object cannot be inserted. 4): The saveorupdate method is used to persistently store objects in the database or update objects. The saveorupdate method has both the SAVE and update functions. The Listener of the SAVE and update methods is the subclass of the listener corresponding to the saveorupdate method. That is, the combination of saveorupdate and save or update methods. You can execute all the functions of save or update, or even replace save or update. However, if we clearly know whether we want to save or update the object, we 'd better use save or update to improve the execution efficiency. This method callsave () or update () based on the operation. This method is called to save () or update () based on the operation. If the identifier exists, it will call update method else the Save method will be called. = "If an identifier exists, it will call the update method; otherwise, it will call the Save method. 5): Update Method Update method in the Hibernate is used for updating the object using identifier The update method is used to update Objects Based on the specified identifier. If the identifier is missing or doesn't exist, it will throw exception. = "If the identifier is lost or does not exist, it will throw an exception.
Chinese version: The saveorupdate () method also contains the functions of the SAVE () and update () methods. If the input parameter is a temporary object, the SAVE () method is called; if the input parameter is a free object, the update () method is called. If the input parameter is a persistent object, the system returns the result directly. So how does the saveorupdate () method determine whether an object is in the temporary or free state? If one of the following conditions is met, Hibernate uses it as a temporary object.
- The OID value of the Java object is null.
- The Java object has the version attribute and the value is null.
- In the ing file, the unsaved-value attribute is set for the <ID> element, and the IOD value matches the unsaved-value attribute value.
- In the ing file, the unsaved-value attribute is set for the version attribute, and the value of the version attribute is the same as that of the unsaved-value attribute.
|
6): If the merge method adds an object and the associated object needs to be echo in the same hibernate session, we recommend that you use the Merge () method. Http://blog.csdn.net/oldcrane/article/details/3837188 7): http://www.blogjava.net/dreamstone/archive/2007/07/29/133071.html of persist Method |
8): Get Method
9): Load Method
Other methods:
1): flush Method
2): Clear Method
3): refresh Method
4): evict Method
2): This. gethibernatetemplate () is supported (). Methods for hql statement operations, we do not need to open and close sessions, connections, sessions and so on, Hibernate and spring have helped us encapsulate. Standard Format: You can use the following code: This. gethibernatetemplate (). Delete (dtree );
Master the usage of the following methods:
Gethibernatetemplate (). Save (entity );
Gethibernatetemplate (). Update (entity );
Gethibernatetemplate (). saveorupdate (entity );
Gethibernatetemplate (). Merge (entity );
Gethibernatetemplate (). persist (entity );
Gethibernatetemplate (). Get (entityclass, ID );
Gethibernatetemplate (). Load (entityclass, ID );
Gethibernatetemplate (). Clear ();
Gethibernatetemplate (). Flush ();
Gethibernatetemplate (). evict (entity );
Gethibernatetemplate (). Refresh (entity );
3 ):
Refer:
Transaction |
beginTransaction() Begin a unit of work and return the associatedTransactionObject |
Query |
createQuery(String queryString) Create a new instanceQueryFor the given hql query string. |
SQLQuery |
createSQLQuery(String queryString) Create a new instanceSqlqueryFor the given SQL query string. |
http://hi.baidu.com/21xionghua/blog/item/199d43fa59e6908b9e5146ad.html
You can use the following method to directly convert SQL queries to list sets.
List catNameList = session.createSQLQuery(sql).addEntity(DocCatalogInfo.class).list();
Which object is associated with the query? How can this problem be solved?
select * from t_user a,t_user_role b where a.c_userid=b.c_userid and a.c_username='admin'
The SQL query can be replaced by the list query, which is more accurate to the string [] array set:select C_ROLEID from t_user a,t_user_role b where a.c_userid=b.c_userid and a.c_username='admin'
[POWERUSERS, ADMINS, USERS, GROUPADMINS]
Void Delete (Object object) removes instances of persistent objects from the database
Get (class clazz, serializable ID) returns the instance of the Persistent Object Based on the given identifier and object class. If no persistence object instance meets the condition, null is returned.
Getsessionfactory () gets the sessionfactory instance that creates this session.
Save (Object object) First generates an identifier for the given free state (transient) object (according to the configuration), assigns a value, and then persists it.
Void saveorupdate (Object object) is based on the value of the Identity attribute of the given instance (Note: unsaved-value can be specified. The default value is null .) To execute the SAVE () or update () operation. Void Update (Object object) updates a persistent instance based on the identifier of the specified detached (idle state) object instance.Query
http://developer.51cto.com/art/200906/130073.htm
- String hql=”from User user ”;
- List list=session.CreateQuery(hql).list();
The code above is executed to query all the data corresponding to the user object, encapsulate the data into the user object, and put it in the list to return.
Iterator |
iterate() Return the query results asIterator. |
List |
list() Return the query results asList. |
int |
executeUpdate() Execute the update or delete statement. |
Batch update: in this way, we can update the batch data at one time in hibernate3, improving the performance. You can also perform the delete operation in a similar way, as shown in the following code:
- Transaction trans = session. begintransaction ();
- String hql = "delete from user where user. Age = 18 ";
- Query queryupdate = session. createquery (hql );
- Int retaskqueryupdate.exe cuteupdate ();
- Trans. Commit ();
- If getcurrentsession is used to create a session, the session is automatically closed after commit, that is, session. Close () is no longer needed. However, if you are using the session created by the opensession or getsession () method, you must disable the session, that is, call the session. Close () method.