Integrate hibernate through Spring and unit test (in detail)

Keywords: Java Hibernate xml Spring Session

I.

If you don't have a basic hibernate foundation, you can click here - ---->. ORM - Hibernate Initial Demo (Invincible Details)

I won't go into details here.

Two.

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 educated to manage Spring.

So you can choose whether to use the hibernate.cfg.xml file or not.

Here we will explain the integration of Spring and Hibernate by using the hibernate.cfg.xml file

Before explaining the integration of Spring and Hibernate, we first need to understand three important objects, which are as follows:

1.HibernateTemplate: session equivalent to Hibernate can directly manipulate PO classes, depending on SessionFactory.

2. LocalSessionFactory Bean: Get SessionFactory.

3. Hibernate Transaction Manager: Hibernate's event manager.

3. Implementation code:

The jar package required for the entire project:

 

1. Integrate Spring with hibernate.cfg.xml file.

First, create a user table:

2. Establishing User Classes

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;
	}
	@Override
	public 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 Mapping DTD 3.0//EN"
	   "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
  <hibernate-mapping>
      <! - name represents the entity class name, table represents the table name - >.
      <class name="com.hck.entity.User" table="user">
          <! -- name = ID represents the field in the table table table - > attribute column=id in the user class
          <id name="id" column="id">
             <! - Primary Key Generation Strategy - >
             <generator class="native"/>
          </id>
          <! - Other attributes are mapped using property tags - >.
          <property name="username" column="username" type="string"/>
          <property name="password" column="password" type="string"/>
      </class>
  </hibernate-mapping>
 

4. Write UserDao interface

public interface UserDao {
  public void save(User user);      //Add user
  public void update(User user);    //Update user
  public void delete(User user);    //delete user
  public User findById(Integer id); //Searching User Data Based on User id
  public List<User>  findAll();     //Return all user data
}

5. Write interface implementation class: UserDaoImpl

//Open Annotation Mode, which is equivalent to spring
//<bean name="userDao" class="com.hck.dao.impl.UserDaoImpl"/>
@Repository("userDao")
public class UserDaoImpl implements UserDao {
	//Dependency injection
	@Autowired
	private HibernateTemplate hibernateTemplate;
	//Insert operation
	public void save(User user) {
          hibernateTemplate.save(user);
	}
    //update operation
	public void update(User user) {
	      hibernateTemplate.update(user);
	}
    //Delete operation
	public void delete(User user) {
		   hibernateTemplate.delete(user);
	}
    //Finding Users Based on ID
	public User findById(Integer id) {	
		return hibernateTemplate.get(User.class, id);
	}
	//Return all user data
	@SuppressWarnings("unchecked")
	public List<User> findAll() {
		return (List<User>) hibernateTemplate.find("from User");
	}
}

6. Writing UserService Interface

public interface UserService {
      public void save(User user);      //Add user
      public void update(User user);    //Update user
      public void delete(User user);    //delete user
      public User findById(Integer id); //According to users id Finding User Data
      public List<User>  findAll();     //Return all user data
}

7. Write UserServiceImpl class

//Open Annotation Mode, which is equivalent to spring
//<bean name="userService" class="com.hck.service.impl.UserServiceImpl"/>
@Service("userService")
public class UserServiceImpl implements UserService {
	//Dependency injection
	@Autowired
	private UserDao userDao;
	//insert data
	public void save(User user) {
		userDao.save(user);	
	}
    //Update data
	public void update(User user) {
	    userDao.update(user);
	}
	//Delete data
	public void delete(User user) {
		userDao.delete(user);	
	}
    //Search for users based on id
	public User findById(Integer id) {	
		return userDao.findById(id);
	}
    //Return all user information
	public List<User> findAll() {
		return userDao.findAll();
	}

}

8. Write 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">
  <hibernate-configuration>
         <session-factory>
	          <!--Designated dialect -->
	          <property name="hibernate.dialect">
	            org.hibernate.dialect.MySQLDialect
	          </property>
	          <!-- Database Driver -->
	          <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
	          <!-- Connecting database url -->
	          <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/tb_test</property>
	          <!-- Database username -->
	          <property name="hibernate.connection.username">root</property>
	          <!-- Database password -->
	          <property name="hibernate.connection.password">123456</property>
	          <!-- Other configurations -->
	          <!-- display sql Sentence -->
	          <property name="show_sql">true</property>
	          <!-- To configure c3p0 -->
	          <property name="hibernate.connection.provider_class">org.hibernate.c3p0.internal.C3P0ConnectionProvider</property>
	          <!-- Used to correlate hbm configuration file -->        
	          <!-- <mapping resource="com/hck/entity/Customer.hbm.xml"/> -->
	          <mapping resource="com/hck/entity/User.hbm.xml"/>
         </session-factory>
  </hibernate-configuration>

9. Write Spring's configuration file, applicationContext.xml, and place it in the src directory as well.

<?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">
     <!-- Open notes -->
     <context:annotation-config/>
     <!-- 1.To configure sessionFactory -->
     <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
     <!-- Load Hibernate Core Profile -->
     <property name="configLocation" value="classpath:hibernate.cfg.xml"/> 
     </bean>
     <!-- 2.To configure Hibernate Template -->
     <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
          <!-- Acquired through factories Session,operation PO class -->
          <property name="sessionFactory" ref="sessionFactory"/>
     </bean>
     <!-- transaction management -->
     <!-- #1 Transaction Manager is the platform, Spring tools are generated, depending on the use of persistent solutions - > 1.
     <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 facets: associating entry points with notification points
     <aop:config>
            <aop:pointcut expression="execution(* com.hck.service.*.*(..))" id="allDaoMethod" />
            <aop:advisor advice-ref="txAdvice" pointcut-ref="allDaoMethod"/>
     </aop:config>
     <!-- Packet scan -->
     <context:component-scan base-package="com.hck"/>
</beans>

Write unit test classes:

public class SpringHibernateTest {
	 //Defining variables 
     ApplicationContext ac;   //Read the Spring configuration file and return the context object
     UserService userService; //To receive an instance of UserService Impl
     @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 User Name
     @Test
     public void update()
     {
    	 User user=new User();
user.setId(1); user.setUsername("Li Si"); user.setPassword("123456"); userService.update(user); } //Find before deleting @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 by the console, and then go to mysql to see if the data was inserted successfully; here I insert two more information users to display and query all user information separately.

B. Query operation (query user id 1 information):

C. Update operation. (Change the username of id=1 to Lisi)

D. Delete operation, (Delete user information with id=1)

 

E. Query all user information

Four. Conclusion

The above is a complete integration process of Spring and Hibernate with hibernate.cfg.xml file. If you have any questions, please leave a message.~

Posted by ONiX on Sun, 19 May 2019 06:01:15 -0700