Spring与Hibernate整合示例详解
简介
在实际开发中,使用Spring和Hibernate框架的组合是比较常见的,这样可以提高开发效率,降低代码耦合度,同时也能够保证数据访问效率。
本文将详细讲解Spring和Hibernate框架的整合过程和使用方法,并且提供两个实例来演示该过程,其中一个是基于XML配置方式,另一个是基于注解配置方式。在学习本文之前,建议先掌握Spring和Hibernate框架的基础知识。
基于XML配置的示例
1、搭建项目环境
首先我们需要创建一个Maven项目,所需依赖如下:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.9</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.9</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.3.9</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.5.7.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.5.7.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
</dependencies>
2、创建实体类
在src/main/java目录下创建一个实体类User,代码如下:
public class User {
private Integer id;
private String name;
private String password;
// getter和setter方法省略
}
3、配置Hibernate
在src/main/resources目录下创建一个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>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test?characterEncoding=utf8&serverTimezone=Asia/Shanghai</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="com.example.demo.entity.User"/>
</session-factory>
</hibernate-configuration>
4、配置Spring
在src/main/resources目录下创建一个applicationContext.xml文件,并添加如下配置:
<?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: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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.example.demo"/>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test?characterEncoding=utf8&serverTimezone=Asia/Shanghai"/>
<property name="username" value="root"/>
<property name="password" value="password"/>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="packagesToScan" value="com.example.demo.entity"/>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
5、创建DAO
在src/main/java目录下创建一个DAO接口UserDao和其实现类UserDaoImpl,代码如下:
public interface UserDao {
void save(User user);
List<User> findAll();
}
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
private SessionFactory sessionFactory;
@Override
@Transactional
public void save(User user) {
sessionFactory.getCurrentSession().save(user);
}
@Override
@Transactional(readOnly = true)
public List<User> findAll() {
return sessionFactory.getCurrentSession().createQuery("from User").list();
}
}
6、测试
在src/test/java目录下创建一个测试类UserServiceTest,代码如下:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class UserServiceTest {
@Autowired
private UserDao userDao;
@Test
public void testSave() {
User user1 = new User();
user1.setName("test1");
user1.setPassword("123456");
User user2 = new User();
user2.setName("test2");
user2.setPassword("123456");
userDao.save(user1);
userDao.save(user2);
}
@Test
public void testFindAll() {
List<User> userList = userDao.findAll();
for (User user : userList) {
System.out.println(user);
}
}
}
执行测试类中的两个方法,可以看到数据成功写入数据库,并且查询结果成功返回。
基于注解配置的示例
1、搭建项目环境
同样需要创建一个Maven项目,并添加与基于XML配置的示例中相同的依赖。
2、创建实体类
同样需要创建一个实体类User,代码如下:
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
@Column(name = "name")
private String name;
@Column(name = "password")
private String password;
// getter和setter方法省略
}
3、配置Hibernate
在src/main/resources目录下创建一个hibernate.properties文件,并添加如下配置:
hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
4、配置Spring
在src/main/resources目录下创建一个applicationContext.xml文件,并添加如下配置:
<?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: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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.example.demo"/>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test?characterEncoding=utf8&serverTimezone=Asia/Shanghai"/>
<property name="username" value="root"/>
<property name="password" value="password"/>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties" ref="hibernateProperties"/>
<property name="packagesToScan" value="com.example.demo.entity"/>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="hibernateProperties"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:hibernate.properties</value>
</list>
</property>
</bean>
</beans>
5、创建DAO
需要创建一个DAO接口UserDao和其实现类UserDaoImpl,并添加注解以支持声明式事务,代码如下:
public interface UserDao {
void save(User user);
List<User> findAll();
}
@Repository
@Transactional
public class UserDaoImpl implements UserDao {
@Autowired
private SessionFactory sessionFactory;
@Override
public void save(User user) {
sessionFactory.getCurrentSession().save(user);
}
@Override
@Transactional(readOnly = true)
public List<User> findAll() {
return sessionFactory.getCurrentSession().createQuery("from User").list();
}
}
6、测试
在src/test/java目录下创建一个测试类UserServiceTest,代码如下:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
@Transactional
public class UserServiceTest {
@Autowired
private UserDao userDao;
@Test
public void testSave() {
User user1 = new User();
user1.setName("test1");
user1.setPassword("123456");
User user2 = new User();
user2.setName("test2");
user2.setPassword("123456");
userDao.save(user1);
userDao.save(user2);
}
@Test
public void testFindAll() {
List<User> userList = userDao.findAll();
for (User user : userList) {
System.out.println(user);
}
}
}
执行测试类中的两个方法,可以看到数据成功写入数据库,并且查询结果成功返回。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:spring结合hibernate示例详解 - Python技术站