Spring整合Hibernate
1. 创建项目
创建一个普通的Maven项目即可
2.添加相关的依赖
代码语言:javascript复制 <dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.8</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.0.7.Final</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
</dependencies>
3. 添加相关的配置文件
添加数据库的配置文件和Spring的配置文件
代码语言:javascript复制<?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/context/spring-tx.xsd
">
<!-- 引入db.properties文件 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- 创建druid 的数据源 -->
<bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
<property name="url" value="${jdbc.url}" />
<property name="driverClassName" value="${jdbc.driver}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- 配置Hibernate的SessionFactory对象 -->
<bean class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" id="sessionFactory">
<!-- 关联数据源 -->
<property name="dataSource" ref="dataSource"/>
<!-- 配置Hibernate的属性信息 -->
<property name="hibernateProperties">
<props>
<prop key="show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<!-- 扫描路径 -->
<property name="packagesToScan">
<list>
<value>com.bobo.pojo</value>
</list>
</property>
</bean>
<!-- 配置HibernateTemplate对象 -->
<bean class="org.springframework.orm.hibernate5.HibernateTemplate" id="hibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- 配置事务管理-->
<bean class="org.springframework.orm.hibernate5.HibernateTransactionManager" id="transactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 配置开启事务注解 -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- 配置扫描路径 -->
<context:component-scan base-package="com.bobo" />
</beans>
4. 创建POJO
和表结构中的t_user表对应即可
代码语言:javascript复制package com.bobo.pojo;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name="t_user")
public class Users implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="user_id")
private Integer userId;
@Column(name="user_name")
private String userName;
@Column(name="real_name")
private String realName;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
}
5. 创建持久层
定义持久层接口,定义要实现的相关的方法
代码语言:javascript复制package com.bobo.dao;
import com.bobo.pojo.Users;
import java.util.List;
public interface IUserDao {
void insertUsers(Users users);
void updateUsers(Users users);
void deleteUsers(Users users);
Users selectUsersById(Integer userId);
List<Users> selectUsersByName(String userName);
List<Users> selectUsersByNameUseSQL(String userName);
List<Users> selectUsersByNameUseCriteria(String userName);
}
代码语言:javascript复制package com.bobo.dao.impl;
import com.bobo.dao.IUserDao;
import com.bobo.pojo.Users;
import jdk.nashorn.internal.ir.annotations.Reference;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public class UserDaoImpl implements IUserDao {
@Autowired
private HibernateTemplate template;
@Override
public void insertUsers(Users users) {
this.template.save(users);
}
@Override
public void updateUsers(Users users) {
this.template.update(users);
}
@Override
public void deleteUsers(Users users) {
this.template.delete(users);
}
@Override
public Users selectUsersById(Integer userId) {
return this.template.get(Users.class,userId);
}
@Override
public List<Users> selectUsersByName(String userName) {
// 我们要执行特殊的查询操作 我们需要获取对应的Session对象
Session session = this.template.getSessionFactory().getCurrentSession();
// 通过Session对象创建Query对象 HQL 语句
Query query = session.createQuery(" from Users where userName = :abc");
Query queryTemp = query.setString("abc", userName);
return queryTemp.list();
}
@Override
public List<Users> selectUsersByNameUseSQL(String userName) {
// 我们要执行特殊的查询操作 我们需要获取对应的Session对象
Session session = this.template.getSessionFactory().getCurrentSession();
// 通过Session对象创建Query对象 SQL 语句
Query query = session.createSQLQuery("select * from t_user where user_name = ?")
.addEntity(Users.class)
.setString(0, userName);
return query.list();
}
@Override
public List<Users> selectUsersByNameUseCriteria(String userName) {
Session session = this.template.getSessionFactory().getCurrentSession();
Criteria criteria = session.createCriteria(Users.class);
criteria.add(Restrictions.eq("userName",userName));
return criteria.list();
}
}
6. 单元测试
代码语言:javascript复制package com.bobo.test;
import com.bobo.dao.IUserDao;
import com.bobo.pojo.Users;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test1 {
@Autowired
private IUserDao dao;
@Test
@Transactional
@Rollback(false)
public void testInsertUser(){
Users user = new Users();
user.setUserName("Tom");
user.setRealName("张三丰");
dao.insertUsers(user);
}
@Test
@Transactional
public void testQuery1(){
Users users = this.dao.selectUsersById(22);
System.out.println(users);
}
@Test
@Transactional
public void testQuery2(){
List<Users> list = this.dao.selectUsersByNameUseSQL("Tom");
for (Users users : list) {
System.out.println(users);
}
}
}