后面几篇文章会详细的介绍SpringData相关的内容,本文先介绍下Spring整合Hibernate的相关内容,如果对于hibernate还不太熟悉可以参考如下的资料补充学习: https://space.bilibili.com/435498550
相关案例代码:https://github.com/q279583842q/springboot-demo-bobokaoya
Spring整合Hibernate
1.创建maven项目
通过IDEA或者Eclipse创建一个简单的maven工程(jar)即可
2.添加相关的依赖
在pom文件中添加如下依赖
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.21.RELEASE</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.8.RELEASE</version> </dependency> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.3</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.0.7.Final</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>4.3.21.RELEASE</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.32</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.21.RELEASE</version> </dependency> </dependencies>
3.添加对应的配置文件
在resources目录下创建spring的配置文件和数据库连接的属性文件,如下:
jdbc.properties文件中的内容:
jdbc.url=jdbc:mysql://localhost:3306/ssm?characterEncoding=utf-8 jdbc.driver.class=com.mysql.jdbc.Driver jdbc.username=root jdbc.password=123456
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: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/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 配置读取properties文件的工具类 --> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- 配置c3p0数据库连接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="driverClass" value="${jdbc.driver.class}"/> <property name="user" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!-- 配置Hibernate的SeesionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- hibernateProperties属性:配置与hibernate相关的内容,如显示sql语句,开启正向工程 --> <property name="hibernateProperties"> <props> <!-- 显示当前执行的sql语句 --> <prop key="hibernate.show_sql">true</prop> <!-- 开启正向工程 --> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> <!-- 扫描实体所在的包 --> <property name="packagesToScan"> <list> <value>com.dpb.pojo</value> </list> </property> </bean> <!-- 配置HiberanteTemplate对象 --> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- 配置Hibernate的事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- 配置开启注解事务处理 --> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- 配置springIOC的注解扫描 --> <context:component-scan base-package="com.dpb"/> </beans>
4.创建pojo
数据的表结构请自行创建一张简单的users表即可,就三个简单的字段(userid,username,userage),pojo如下:
/** * @program: spring-hibernate * @description: Users的Pojo对象 * @author: 波波烤鸭 * @create: 2019-05-18 09:37 */ @Entity @Table(name="users") public class Users implements Serializable { @Id @GeneratedValue(strategy= GenerationType.IDENTITY)//strategy=GenerationType.IDENTITY 自增长 @Column(name="userid") private Integer userid; @Column(name="username") private String username; @Column(name="userage") private Integer userage; 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 Integer getUserage() { return userage; } public void setUserage(Integer userage) { this.userage = userage; } @Override public String toString() { return "Users [userid=" + userid + ", username=" + username + ", userage=" + userage + "]"; } }
5.创建持久层的接口和实现
创建持久层的Dao接口和实现类,具体如下:
/** * 定义接口中的方法 */ public interface UserDao { void insertUsers(Users users); void updateUsers(Users users); void deleteUsers(Users users); Users selectUsersById(Integer userid); List<Users> selectUserByName(String username); List<Users> selectUserByNameUseSQL(String username); List<Users> selectUserByNameUseCriteria(String username); }
实现类----注意导入的jar包
import com.dpb.dao.UserDao; import com.dpb.pojo.Users; 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; /** * @program: spring-hibernate * @description: 用户持久层的实现类 * @author: 波波烤鸭 * @create: 2019-05-18 09:43 */ @Repository public class UserDaoImpl implements UserDao { @Autowired private HibernateTemplate hibernateTemplate; @Override public void insertUsers(Users users) { this.hibernateTemplate.save(users); } @Override public void updateUsers(Users users) { this.hibernateTemplate.update(users); } @Override public void deleteUsers(Users users) { this.hibernateTemplate.delete(users); } @Override public Users selectUsersById(Integer userid) { return this.hibernateTemplate.get(Users.class, userid); } /** * HQL 使用 * @param username * @return */ @Override public List<Users> selectUserByName(String username) { //getCurrentSession:当前session必须要有事务边界,且只能处理唯一的一个事务。当事务提交或者回滚后session自动失效 //openSession:每次都会打开一个新的session.加入每次使用多次。则获得的是不同session对象。使用完毕后我们需要手动的调用colse方法关闭session Session session = this.hibernateTemplate.getSessionFactory().getCurrentSession(); //sql:select * from t_users where username = Query query = session.createQuery(" from Users where username = :abc"); Query queryTemp = query.setString("abc",username); return queryTemp.list(); } /** * SQL 的使用 * @param username * @return */ @Override public List<Users> selectUserByNameUseSQL(String username) { Session session = this.hibernateTemplate.getSessionFactory().getCurrentSession(); Query query = session.createSQLQuery("select * from t_users where username = ?").addEntity(Users.class).setString(0, username); return query.list(); } /** * Criteria * @param username * @return */ @Override public List<Users> selectUserByNameUseCriteria(String username) { Session session = this.hibernateTemplate.getSessionFactory().getCurrentSession(); //sql:select * from t_users where username = 张三 Criteria c = session.createCriteria(Users.class); c.add(Restrictions.eq("username", username)); return c.list(); } }
6.单元测试
在test目录下创建单元测试类,测试相关的操作
/** * @program: spring-hibernate * @description: 单元测试 * @author: 波波烤鸭 * @create: 2019-05-18 09:48 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class TestDemo { @Autowired private UserDao usersDao; /** * 添加用户 */ @Test @Transactional// 在测试类对于事务提交方式默认的是回滚。 @Rollback(false)//取消自动回滚 public void testInsertUsers(){ Users users = new Users(); users.setUserage(20); users.setUsername("张三"); this.usersDao.insertUsers(users); } /** * 更新用户 */ @Test @Transactional @Rollback(false) public void testUpdateUsers(){ Users users = new Users(); users.setUserid(2); users.setUserage(22); users.setUsername("李四"); this.usersDao.updateUsers(users); } /** * 根据userid查询用户 */ @Test public void testSelectUsersById(){ Users users = this.usersDao.selectUsersById(2); System.out.println(users); } /** * 删除用户 */ @Test @Transactional @Rollback(false) public void testDeleteUsers(){ Users users = new Users(); users.setUserid(2); this.usersDao.deleteUsers(users); } /** * HQL测试 */ @Test @Transactional public void testSelectUserByName(){ List<Users> list = this.usersDao.selectUserByName("张三"); for (Users users : list) { System.out.println(users); } } /** * SQL测试 */ @Test @Transactional public void testSelectUserByNameUseSQL(){ List<Users> list = this.usersDao.selectUserByNameUseSQL("张三"); for (Users users : list) { System.out.println(users); } } /** * Criteria测试 */ @Test @Transactional public void testSelectUserByNameUseCriteria(){ List<Users> list = this.usersDao.selectUserByNameUseCriteria("张三"); for (Users users : list) { System.out.println(users); } } }
操作成功~