Spring + hibernate Dao persistence layer development. Spring uses three methods for accessing the database using hibernate. Callback is recommended.

Source: Internet
Author: User

Dao Development

Note:
(1) both of the following must be registered in the spring xml configuration file bean (Implementation class) to inject sessionfactory dependencies.
(2.1) the general method of Transaction Management in spring is to use AOP (for slicing programming) to encapsulate transaction control for common Java classes. It is implemented through dynamic proxy, because the interface is
Delayed instantiation, spring loads transaction slices through the interceptor during this period. This is the principle. For details, see the documentation on dynamic proxy in JDK. This article mainly explains
How to control transactions in spring.
(2.2) an important feature of dynamic proxy is that it targets interfaces, so our Dao should let spring take over transactions through dynamic proxy, an interface must be abstracted before Dao. of course
Without such an interface, spring will use cglib to solve the problem, but this is not the method recommended by spring.

(1) directly use the hibernate API (not recommended)
Public class daoimp implate Dao {
Private sessionfactory;
Private Static string hql = "from user u where u. Username =? ";

Public void setsessionfactory (sessionfactory ){
This. sessionfactory = sessionfactory;
}

Public Boolean isvaliduser (string username ){
Try {
List userlist = sessionfactory. getcurrentsession (). creatquery (hql). setparameter (0, username). List ();
If (userlist. Size ()> 0 ){
Return true;
} Catch (hibernateexception ex ){
Throw converhibernateraccessexception (Ex );
}
}
}

Advantage: completely isolated from the Spring framework
Disadvantages: (1) You cannot use the Spring framework to encapsulate the additional functions provided. For example, you need to try... catch () to directly use the hibernate API to handle the hibernateexception exception.
(2) The setsessionfactory (sessionfactory) attribute must be added to the implementation class to receive sessionfactory from dependency injection.

(2) inherit from spring's hibernatedaosupport using hibernatetemplate (getsession () is not recommended ())
Public class daoimp extend hibernatedaosupport implates Dao {
// Private sessionfactory;
Private Static string hql = "from user u where u. Username =? ";

// Public void setsessionfactory (sessionfactory ){
// This. sessionfactory = sessionfactory;
//}

Public Boolean isvaliduser (string username ){
// Try {
// List userlist = sessionfactory. getcurrentsession (). creatquery (hql). setparameter (0, username). List ();
List userlist = gethibernatetemplate (). Find (hql, username );
If (userlist. Size ()> 0 ){
Return true;
//} Catch (hibernateexception ex ){
// Throw converhibernateraccessexception (Ex );
//}
}

Public Boolean isvaliduser (string username, string password) Throw dataaccessexception {
Session session = getsession (); // this parameter is not recommended and must be disabled manually after use.
String [] userlist = new string [2];
Userlist [0] = username;
Userlist [1] = password;
Try {
List userlist = session. Find (hql, userlist); // hibernate statement;
Session. Close ();
If (userlist. Size ()> 0 ){
Return true;
} Catch (hibernateexception ex ){
Throw converhibernateraccessexception (Ex );
}
}
}

Features: this function is not provided for hibernatetemplate. You can directly call the getsession () method of the hibernatedaosuppor object (not recommended) to obtain the session object instance. Use try {hibernate API} catch (hibernateexception ex) operation.

(3) functions not provided for hibernatetemplate. You can also use the hibernatecallback callback method to manage the database. (recommended)

/**
* Use hql statements for operations
* @ Param hql hsql query statement
* @ Param offset start to obtain the subscript of the data
* @ Param length: number of data records read
* @ Return list result set
*/
Public list getlistforpage (final string hql, final int offset, final int length ){

List list = gethibernatetemplate(cmd.exe cutefind (New hibernatecallback (){
Public object doinhibernate (session) throws hibernateexception, sqlexception {
Query query = session. createquery (hql );
Query. setfirstresult (offset );
Query. setmaxresults (length );
List list = query. List ();
Return list;
}
});
Return list;
}

 

 

 

Methods for accessing databases using Dao in spring + hibernate Architecture
In the spring + hibernate architecture, there are several methods to access the database. There are three methods based on Spring dependency injection. Before that, let's take a look at Spring dependency injection, the two main cores of spring are IOC (control inversion) and AOP (for Aspect-Oriented Programming). Control inversion is to control transfer, in the past, bean was used to control the interface to be called or transfer other resources to the container, and the container was used to find and instantiate the interface to be called. It can also be interpreted as dependency injection, that is, in the Spring configuration file, the interface to be called, settings, and construction sub-configuration are sent to bean. Here, dependency injection is used to distinguish between sessionfactory, hibernatetemplate, and jdbctemplate. Basically, only hibernatetemplate and jdbctemplate are divided. 1. Inject sessionfactory
In the spring configuration file, inject sessionfactory to Dao, that is:
<Bean id = "classdao" class = "cn. jmu. Data. Dao. impl. classimpl">
<Property name = "sessionfactory">
<Ref local = "sessionfactory"/>
</Property>
</Bean>
Here, sessionfactory does not inject dependencies to classes in the DaO layer, but to hibernatedaosupport. For details, see the spring source file ORG/springframework/ORM/hibernate3/support/hibernatedaosupport. in Java, the set and get operations of sessionfactory are as follows: public final void setsessionfactory (sessionfactory ){
This. hibernatetemplate = createhibernatetemplate (sessionfactory); // generate hibernatetemplate through sessionfactory
} Public final sessionfactory getsessionfactory (){
Return (this. hibernatetemplate! = NULL? This. hibernatetemplate. getsessionfactory (): NULL );
} So in the DaO layer, the class inherits hibernatedaosupport and you can use this. gethibernatetemplate () to operate the database,
Update Data: This. gethibernatetemplate (). Update (BO );
Query data: This. gethibernatetemplate (). Find (BO );
Add data: This. gethibernatetemplate (). Save (BO );
Delete data: This. gethibernatetemplate (). Delete (BO );
We can see from the above that the powerful power of spring + hibernate does not need to write a large series of try and catch statements to access data, just like JDBC in the past. It also needs to connect to the database and close the database connection after it is used up, you can use one statement.
Here sessionfactory is automatically connected and closed by spring. Of course, you can also manually connect and close it, as shown in the following method:
Session session = This. gethibernatetemplate (). getsessionfactory (). opensession ();
Transaction Tx = session. begintransaction ();
/* -------------- Query data ------------------------*/
String STR = "hql ";
Query query = session. createquery (STR );
List list = query. List ();
/* -------------- Delete data ------------------------*/
Session. Load (Bo, ID );
Session. Delete (BO );
/* -------------- Add data ------------------------*/
Session. Save (BO );
/* -------------- Modify data -----------------------*/
Session. Load (Bo, ID );
Session. Update (BO );
/* -------------- End ---------------------------*/
TX. Commit ();
Session. Close ();
People who are new to hebernate should be familiar with the code. Without the hibernatetemplate provided by spring, they must access and access data in hibernate alone.
2. Inject hibernatetemplate
This method is essentially the same as the above injection of sessionfactory, but it only needs to be packaged. The biggest advantage is that the classes in Dao no longer need to inherit hibernatedaosupport (in Java, they are individually inherited, it is a pity that the only inheritance was denied by hibernatedaosupport ?) However, you must configure the hibernatetemplate before doing so, that is:
<Bean id = "hibernatetemplate" class = "org. springframework. Orm. hibernate3.hibernatetemplate">
<Property name = "sessionfactory">
<Ref bean = "sessionfactory"/>
</Property>
</Bean>
Then inject the dependency of Dao that uses hibernatetemplate, that is:
<Bean id = "classdao" class = "cn. jmu. Data. Dao. impl. classimpl">
<Property name = "hibernatetemplate">
<Ref bean = "hibernatetemplate"/>
</Property>
</Bean>
Add the hibernatetemplate object to the class at the DaO layer to correspond to the dependencies injected in the configuration file:
Private hibernatetemplate;
Public hibernatetemplate gethibernatetemplate (){
Return hibernatetemplate;
}
Public void sethibernatetemplate (hibernatetemplate ){
This. hibernatetemplate = hibernatetemplate;
}
The addition, deletion, and query of data by hibernatetemplate are the same as the following:
Update Data: hibernatetemplate (). Update (BO );
Query data: hibernatetemplate (). Find (BO );
Add data: hibernatetemplate (). Save (BO );
Delete data: hibernatetemplate (). Delete (BO );
3. Inject jdbctemplate. If you still remember the previous jdbc SQL statements and do not like hql of hibernate, you can use jdbctemplate to add, delete, query, and modify databases. In some cases, using jdbctemplate is more convenient and can even improve the query efficiency. Before that, configure jdbctemplate and <bean id = "jdbctemplate" class = "org. springframework. JDBC. Core. jdbctemplate">
<Property name = "datasource">
<Ref bean = "datasource"/>
</Property>
</Bean> if both jdbctemplate and hibernatetemplate point to the same datasource, you can share the same transaction. Then inject the dependency on the DaO that uses jdbctemplate, that is, <bean id = "classdao" class = "cn. jmu. Data. Dao. impl. classimpl">
<Property name = "jdbctemplate">
<Ref bean = "jdbctemplate"/>
</Property>
</Bean> the jdbctemplate object must be added to the classes at the DaO layer to correspond to the dependencies injected in the configuration file: protected jdbctemplate; Public jdbctemplate getjdbctemplate (){
Return jdbctemplate;
} Public void setjdbctemplate (jdbctemplate ){
This. jdbctemplate = jdbctemplate;
} Now you can access data through jdbctemplate: query data:
/* ------------ Query a single column -------------------*/
String SQL = "Select name from table ";
List list = jdbctemplate. queryforlist (SQL );
/* ------------ Query multiple columns ------------------*/
Hashtable hash = new hashtable ();
Jdbctemplate. Query (SQL,
New rowcallbackhandler (){
Public void processrow (resultset RS) throws sqlexception {
Hash. Put (Rs. getstring (1), RS. getstring (2 ));
}
});
/* ---------- Fill in the vo after the query -----------*/
String SQL = "select * from table where id =? ";
String [] OBJ = new string [1];
OBJ [0] = N;
VO Vo = new VO (); // The vo is used for the moment. This is not the essence of VO.
List list = jdbctemplate. Query (SQL, OBJ, VO );
VO needs to implement the maprow method in the rowmapper interface and fill the result set in the BO: Class VO implements rowmapper {
Public object maprow (resultset RS, int index) throws sqlexception {
Bo = new Bo ();
Bo. setproperty (Rs. getstring (1 ));
Bo. setproperty (Rs. getstring (2 ));
Bo. setproperty (Rs. getstring (3 ));
Return Bo;
}
}/* ---------------- Update data ------------------*/
String SQL = "Update table set name =? ";
String [] OBJ = new string [1];
OBJ [1] = "new name ";
Jdbctemplate. Update (SQL, OBJ );
/* ---------------- Delete data ------------------*/
String SQL = "delete from table where id = '" + ID + "'";
Jdbctemplate.exe cute (SQL );
/* ---------------- Add data ------------------*/
String SQL = "insert into table (property1, property2) values ('" + property1 + "', '" + property1 + "')";
Jdbctemplate.exe cute (SQL );

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.