SSH journey (5) apply Spring to Hibernate

Source: Internet
Author: User

Spring and hibernate.

Simple Hibernate Program

1. First, import the jar package of hibernate. For the steps, see.

2. Create User and User operation record entities, Log. java and User. java. The Code is as follows.

Log. java

Import java. util. date; public class Log {private int id; // Log category. logs are undeniable. // operation log security log event log. private String type; private String detail; private Date time; public int getId () {return id;} public void setId (int id) {this. id = id;} public String getType () {return type;} public void setType (String type) {this. type = type;} public String getDetail () {return detail;} public void setDetail (String detail) {this. detail = detail;} public Date getTime () {return time;} public void setTime (Date time) {this. time = time ;}}
User. java

public class User {private int id;private String name;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}}


3. Create the corresponding object configuration file Log. hbm. xml and Use. hbm. xml. The Code is as follows.

 
 
  
   
    
   
   
  
 

Log. hbm. xml

 
 
  
   
    
   
   
   
   
  
 


4. The Manager layer code is as follows.

LogManager. java Interface

Public interface LogManager {// Add a Log. Method public void addLog (log Log );}

LogManagerImpl implementation

public class LogManagerImpl implements LogManager {@Overridepublic void addLog(Log log) {HibernateUtils.getSessionFactory().getCurrentSession().save(log);}}


UserManager Interface

public interface UserManager {public void addUser(User user);}


UserManagerImpl. java implementation

Public class UserManagerImpl implements UserManager {@ Overridepublic void addUser (User user) {Session session = null; try {// put this session in threadlocal. session = HibernateUtils. getSessionFactory (). getCurrentSession (); session. beginTransaction (); // Add one in the User table and one in the log. session. save (user); Log log = new Log (); log. setType ("operation log"); log. setTime (new Date (); log. setDetail ("xxx"); LogManager logManager = new LogManagerImpl (); // Add logs. logManager. addLog (log); session. getTransaction (). commit ();} catch (Exception e) {e. printStackTrace (); session. getTransaction (). rollback ();} finally {HibernateUtils. closeSession (session );}}}


5. The session is created through sessionFactory, And the commit and rollback transactions are started through the session. We encapsulate the Enable and close the session into a tool class. The Code of HibernateUtils. java is as follows.

Public class HibernateUtils {private static SessionFactory factory; static {try {// read hibernate. cfg. xml file Configuration cfg = new Configuration (). configure (); // create SessionFactoryfactory = cfg. buildSessionFactory ();} catch (Exception e) {e. printStackTrace () ;}} public static Session getSession () {return factory. openSession ();} public static void closeSession (Session session) {if (session! = Null) {if (session. isOpen () {session. close () ;}} public static SessionFactory getSessionFactory () {return factory ;}}


6. Configure the hibernate. cfg. xml file, including the database name, table associated with the database, and user name and password. The Code is as follows.

 
  
   
    com.mysql.jdbc.Driver
   
   
    jdbc:mysql://localhost:3306/spring_hibernate_1
   
   
    root
   
   
    root
   
   
    org.hibernate.dialect.MySQLDialect
   
   
    true
   
   
    update
   
   
    thread
   
   
   
   
  
 


7. Use junit for unit testing. The Code is as follows.

Import junit. framework. testCase; public class UserManagerImplTest extends TestCase {public void testAddUser () {UserManager userManager = new UserManagerImpl (); User user User = new user (); User. setName ("Zhang San"); userManager. addUser (user );}}


In the above operation, the control boundary of the transaction is in the business logic layer, because in UserManagerImpl, We need to write this operation into the log while calling the addUser () method, that is, the addLog () method is called. For the class method, one method, one session, and one transaction, what if the transaction is controlled? Do we need to start the addUser () Transaction and then the addLog () transaction? Here we have not used the previous openSession method again. We chose to use the HibernateUtils. getSessionFactory (). getCurrentSession (). At the same time, we have configured getCurrentSession () in hibernate. cfg. xml as follows, ThreadIn the current thread, bind it to the current thread to execute the addUser () method and the addLog () method using the same transaction.


What is the difference between OpenSession and getCurrentSession?

1. openSession must be closed, and currentSession will be closed automatically after the transaction ends.

2. openSession is not bound to the current thread, and currentSession is bound to the current thread. In addition, to use currentSession, You need to configure the transaction in our hibernate. cfg. xml file, whether it is a Jdbc transaction or a JTA transaction.

Combined Use of hibernate and spring

From the above example, we found that the hibernate transaction is independent from the addition, deletion, modification, and query of the database by hibernate, and the transaction is controlled at our business logic layer. For the independent thing, for example, we naturally think of AOP as a cross-cutting problem. In fact, SpringAOP encapsulates transaction management. Using SpringAOP, we are no longer responsible for starting and closing transactions.

Spring AOP is used in combination with hibernate.

Of course, we also need to import jar related to Spring. The previous article has already described it.

Transaction Management is a cross-cutting problem. modularization of transaction management is our aspect. Then we can configure the transaction in the configuration file. We can put the transaction in a configuration file separately.

1. The Code is as follows, applicationContext-common.xml file.
 
  
  
   
    
     
Classpath: hibernate. cfg. xml
    
   
  
  
  
   
    
   
  
  
  
   
    
    
    
    
   
  
 


The first step is to configure sessionFactory so that spring can get the sessionFactory of hibernate to control hibernate transactions and generate session access through sessionFactory. In this way, the sessionFactory of hibernate is injected into Spring. Pass Label to tell spring hibernate where the configuration file is, so that spring can read the hibernate configuration file.

The second step is to configure the Transaction Manager and inject our sessionFactory into the transaction manager so that the transaction manager can manage the transaction.

Next, which methods are used to execute the transaction at the beginning,

Second, configure AOP, expression = "execution (* com. bjpowernode. usermgr. manager. *. * (..)". which classes are handed over to spring for transaction management? We apply all the methods in all manager packages, and all the methods in all manager classes participate in the transaction operation. Where can I start the transaction?

Once again, define an Advice and configure the propagation feature of the transaction. For example, if addLog () is called in addUser (), it is in the same transaction or not in the same transaction. Starting with "add", "del", "modify", and others, the transaction propagation feature we configure is propagation = "REQUIRED". In this way, a common thread is called for another method in one method.

2. Let UserManagerImpl inherit the hibernateDao Support class provided by spring.

HibernateDaoSupport. After inheritance, we can get the session, which is actually the session in hibernate, but spring encapsulates it for us. We can get the sesion: This. getSession (). save (user); or use the spring encapsulated object: This. getHibernateTemplate (). save (user); is encapsulated in this way, so we do not manage the opening or closing of transactions.

Previously, we used the LogManagerImpl instance in our UserManagerImpl. This time, we can use the Spring IOC container to inject the dependencies between them into Spring. In this way, we can't see the instance and face interface programming, decoupled.

The interface remains unchanged. The UserManagerImpl. java code is as follows.

Public class UserManagerImpl extends HibernateDaoSupport implements UserManager {private LogManager logManager; public void setLogManager (LogManager logManager) {this. logManager = logManager;} @ Overridepublic void addUser (User user) throws Exception {// this. getSession (). save (user); // or use. this. getHibernateTemplate (). save (user); Log log = new Log (); log. setType ("operation log"); log. setTime (new Date (); log. setDetail ("xxx"); // LogManager logManager = new LogManagerImpl (); // Add logs. logManager. addLog (log); // an exception occurs during runtime and will be rolled back. and its subclass will also roll back. // throw new RuntimeException (); // throw new Exception ();}}


The LogManagerImpl. java code is as follows.

public class LogManagerImpl extends HibernateDaoSupport implements LogManager {@Overridepublic void addLog(Log log) {//getSession().save(log);this.getHibernateTemplate().save(log);}}


Delete the self-created HibernateUtils. java class and delete the transaction configuration of getCurrentSession () in the hibernate. cfg. xml file.

3. Configure the dependency in the configuration file.

The applicationContext-beans.xml code is as follows.

 
  
   
   
  
  
   
  
 


The following code is tested in Junit.

Public class UserManagerImplTest extends TestCase {public void testAddUser () {BeanFactory factory = new ClassPathXmlApplicationContext ("applicationContext -*. xml "); UserManager userManager = (UserManager) factory. getBean ("userManager"); User user User = new user (); User. setName ("Zhang San"); try {userManager. addUser (user);} catch (Exception e) {e. printStackTrace ();}}}


Shows the result.


In this way, the combination of spring and hibernate is completed. Spring AOP is used to control hibernate transactions and spring IOC is used to control calls between the Manager layer.

Next, combine Spring with Struts.

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.