Integrate hibernate with Spring for unit testing (detailed) and hibernate for unit testing
I.
If you do not have basic hibernate, click here ----------> ORM ---- hibernate getting started Demo (invincible detailed version)
I will not introduce it in detail here ..
II.
The hibernat. cfg. xml file is an important configuration file in Hibernate. When Spring and Hibernate are integrated, the configuration information in the hibernate. cfg. xml file can be managed by Spring,
Therefore, you can choose whether to use the hibernate. cfg. xml file.
Here we will use the hibernate. cfg. xml file to explain the integration of Spring and Hibernate.
Before explaining the integration of Spring and Hibernate, you need to understand three important objects:
1. HibernateTemplate: equivalent to the Hibernate session, which can directly operate the PO class and relies on SessionFactory.
2. LocalSessionFactoryBean: Get SessionFactory.
3. HibernateTransactionManager: Hibernate's Transaction Manager.
Iii. Implementation Code:
Jar packages required for the entire project:
1. Use the hibernate. cfg. xml file to integrate Spring.
1) first create a user table:
2) create a User class
Public class User {private Integer id; // User id private String username; // User name private String password; // User password public Integer getId () {return id ;} public void setId (Integer id) {this. id = id;} public String getUsername () {return username;} public void setUsername (String username) {this. username = username;} public String getPassword () {return password;} public void setPassword (String password) {this. password = password ;}@ Overridepublic String toString () {return "User [id =" + id + ", username =" + username + ", password = "+ password +"] ";}}
3) write the corresponding User. hbm. xml
<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE hibernate-mapping PUBLIC "-// Hibernate/Hibernate DTD ing DTD 3.0 // EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
4). Compile the UserDao Interface
Public interface UserDao {public void save (User user User); // Add the user public void update (User user User); // update the user public void delete (User user ); // Delete the public User findById (Integer id); // search for the public List of User data based on the User id <User> findAll (); // return all User data}
5). Write the interface implementation class: UserDaoImpl
// Enable the annotation mode, which is equivalent to in spring // <bean name = "userDao" class = "com. hck. dao. impl. userDaoImpl "/> @ Repository (" userDao ") public class UserDaoImpl implements UserDao {// dependency injection @ Autowiredprivate HibernateTemplate hibernateTemplate; // insert public void save (User user) {response. save (user) ;}// update public void update (User user) {hibernateTemplate. update (user) ;}// delete public void delete (User user) {hibernateTemplate. delete (user);} // search for the User's public user findById (Integer ID) {return hibernateTemplate by id. get (User. class, id) ;}// returns all User data @ SuppressWarnings ("unchecked") public List <User> findAll () {return (List <User>) hibernateTemplate. find ("from User ");}}
6) Compile the UserService Interface
Public interface UserService {public void save (User user User); // Add the user public void update (User user User); // update the user public void delete (User user ); // Delete the public User findById (Integer id); // search for the public List of User data based on the User id <User> findAll (); // return all User data}
7). Compile the UserServiceImpl class
// Enable the annotation mode, which is equivalent to in spring // <bean name = "userService" class = "com. hck. service. impl. userServiceImpl "/> @ Service (" userService ") public class UserServiceImpl implements UserService {// dependency injection @ Autowiredprivate UserDao userDao; // insert public void save (User user User) {userDao. save (user) ;}// update public void update (User user) {userDao. update (user) ;}// delete public void delete (User user) {userDao. delete (user);} // search for the User's public user findById (Integer id) {return userDao by id. findById (id);} // returns all User information. public List <User> findAll () {return userDao. findAll ();}}
8). Compile the core configuration file hibernate. cfg. xml.
<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE hibernate-configuration PUBLIC "-// Hibernate/Hibernate Configuration DTD 3.0 // EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
9) Compile the Spring configuration file applicationContext. xml and put it under the src directory.
<? Xml version = "1.0" encoding = "UTF-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: context = "http://www.springframework.org/schema/context" xmlns: aop = "http://www.springframework.org/schema/aop" xmlns: tx = "http://www.springframework.org/schema/tx" xsi: schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans. Xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd "> <! -- Enable annotation --> <context: annotation-config/> <! -- 1. Configure sessionFactory --> <bean id = "sessionFactory" class = "org. springframework. orm. hibernate5.LocalSessionFactoryBean"> <! -- Load the core configuration file of Hibernate --> <property name = "configLocation" value = "classpath: hibernate. cfg. xml"/> </bean> <! -- 2. Configure the Hibernate template --> <bean id = "hibernateTemplate" class = "org. springframework. orm. hibernate5.HibernateTemplate"> <! -- Get the Session through the factory and operate the PO class --> <property name = "sessionFactory" ref = "sessionFactory"/> </bean> <! -- Transaction Management --> <! -- #1 the Transaction Manager is generated by the Sprring tool on the platform and depends on the persistent solution. --> <bean id = "txManager" class = "org. springframework. orm. hibernate5.HibernateTransactionManager "> <property name =" sessionFactory "ref =" sessionFactory "/> </bean> <! -- #2 notification: enhanced transaction --> <tx: advice id = "txAdvice" transaction-manager = "txManager"> <tx: attributes> <tx: method name = "save *"/> <tx: method name = "update *"/> <tx: method name = "delete *"/> <! -- Read-only --> <tx: method name = "find *" read-only = "true"/> </tx: attributes> </tx: advice> <! -- #3: Associate the entry point with the notification point --> <aop: config> <aop: pointcut expression = "execution (* com. hck. service. *. *(..)) "id =" allDaoMethod "/> <aop: advisor advice-ref =" txAdvice "pointcut-ref =" allDaoMethod "/> </aop: config> <! -- Package scan --> <context: component-scan base-package = "com. hck"/> </beans>
10). Write unit test classes:
Public class SpringHibernateTest {// defines the variable ApplicationContext ac; // reads the Spring configuration file and returns the context object UserService userService; // receives a UserServiceImpl instance @ Before public void setUp () {ApplicationContext ac = new ClassPathXmlApplicationContext ("applicationContext. xml "); userService = (UserService) ac. getBean ("userService") ;}@ Test public void insert () {User user = new User (); user. setUsername ("Zhang San"); user. setPassword ("123456"); userService. save (user) ;}@ Test public void findById () {User user = userService. findById (1); System. out. println (user);} // modify the username @ Test public void update () {User user = new User ();
User. setId (1); user. setUsername ("Li Si"); user. setPassword ("123456"); userService. update (user) ;}// first search and then delete @ Test public void delete () {User user = userService. findById (1); userService. delete (user) ;}// find all @ Test public void findAll () {List <User> list = userService. findAll (); for (User user: list) {System. out. println (user );}}}
11) test results:
A. insert operation:
The SQL statement printed on the console is then displayed in mysql to check whether the data is successfully inserted. Here, I insert two more messages to display the information of all users separately.
B. query operations (query information with user ID 1 ):
C. Update (change the user name with id = 1 to Li Si)
D. Delete (delete user information with id = 1)
E. query all user information
Iv. Summary
The above is the complete process of integrating Spring and hibernate with the Hibernate. cfg. xml file. If you have any questions, please leave a message ~