当前位置: 代码迷 >> 综合 >> SpringData【Spring整合HibernateJPA】
  详细解决方案

SpringData【Spring整合HibernateJPA】

热度:4   发布时间:2023-12-22 18:32:44.0

??本文在上一篇‘Spring整合hibernate’的基础上来介绍下Spring整合HibernateJPA的内容,

Spring整合HibernateJPA

一、什么是JPA

??现如今的ORM框架还是比较多的比如Hibernate,TopLink以及OpenJPA等等,为了简化ORM框架的使用,JPA随之产生。
??JPA是Java Persistence API的简称,中文名Java持久层API,由 Sun 公司提供了一对对于持久层操作的标准(接口+文档),说白了就是在各种ORM框架之上封装了一套API实现统一操作。同时又依赖各种ORM框架去实现。hibernate3.2版本后提供了对JPA的实现。本文就具体来介绍下怎么使用

二、整合HibernateJPA

1.创建maven项目

??创建一个普通maven工程(jar)

2.引入相关的依赖

<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><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-entitymanager</artifactId><version>5.0.7.Final</version></dependency>
</dependencies>

3.添加配置文件

jdbc.url=jdbc:mysql://localhost:3306/ssm?characterEncoding=utf-8
jdbc.driver.class=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=123456
<?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.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsdhttp://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><!-- Spring 整合 JPA 配置 EntityManagerFactory--><bean id="entityManagerFactory"class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"><property name="dataSource" ref="dataSource"/><property name="jpaVendorAdapter"><bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"><!-- hibernate 相关的属性的注入 --><!-- 配置数据库类型 --><property name="database" value="MYSQL"/><!-- 正向工程 自动创建表 --><property name="generateDdl" value="true"/><!-- 显示执行的 SQL --><property name="showSql" value="true"/></bean></property><!-- 扫描实体的包 --><property name="packagesToScan"><list><value>com.dpb.pojo</value></list></property></bean><!-- 配置 Hibernate 的事务管理器 --><bean id="transactionManager"class="org.springframework.orm.jpa.JpaTransactionManager"><property name="entityManagerFactory"ref="entityManagerFactory"/></bean><!-- 配置开启注解事务处理 --><tx:annotation-driven transaction-manager="transactionManager"/><!-- 配置springIOC的注解扫描 --><context:component-scan base-package="com.dpb"/>
</beans>

4.添加pojo

/*** @program: spring-hibernate-jpa* @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;}@Overridepublic 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);
}
import org.springframework.stereotype.Repository;import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;/*** @program: spring-hibernate* @description: 用户持久层的实现类* @author: 波波烤鸭* @create: 2019-05-18 09:43*/
@Repository
public class UserDaoImpl implements UserDao {
    @PersistenceContext(name="entityManagerFactory")private EntityManager entityManager;@Overridepublic void insertUsers(Users users) {
    this.entityManager.persist(users);}@Overridepublic void updateUsers(Users users) {
    this.entityManager.merge(users);}@Overridepublic void deleteUsers(Users users) {
    Users  u = this.selectUsersById(users.getUserid());this.entityManager.remove(u);}@Overridepublic Users selectUsersById(Integer userid) {
    return this.entityManager.find(Users.class, userid);}@Overridepublic List<Users> selectUserByName(String username) {
    return this.entityManager.createQuery(" from Users where username = :abc").setParameter("abc", username).getResultList();}@Overridepublic List<Users> selectUserByNameUseSQL(String username) {
    //在Hibernate JPA中 如果通过?方式来帮顶参数,那么他的查数是从1开始的。而hibernate中是从0开始的。return this.entityManager.createNativeQuery("select * from t_users where username = ?", Users.class).setParameter(1, username).getResultList();}@Overridepublic List<Users> selectUserByNameUseCriteria(String username) {
    //CriteriaBuilder对象:创建一个CriteriaQuery,创建查询条件。CriteriaBuilder builber = this.entityManager.getCriteriaBuilder();//CriteriaQuery对象:执行查询的Criteria对象//select * from t_usersCriteriaQuery<Users> query = builber.createQuery(Users.class);//获取要查询的实体类的对象Root<Users> root = query.from(Users.class);//封装查询条件Predicate cate = builber.equal(root.get("username"), username);//select * from t_users where username = 张三query.where(cate);//执行查询TypedQuery<Users> typeQuery = this.entityManager.createQuery(query);return typeQuery.getResultList();}
}

6.单元测试


/*** @program: spring-hibernate* @description: 单元测试* @author: 波波烤鸭* @create: 2019-05-18 09:48*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestDemo {
    @Autowiredprivate UserDao usersDao;/*** 添加用户*/@Test@Transactional// 在测试类对于事务提交方式默认的是回滚。@Rollback(false)//取消自动回滚public void testInsertUsers(){
    Users users = new Users();users.setUserage(20);users.setUsername("张三-jpa");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查询用户*/@Testpublic 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@Transactionalpublic void testSelectUserByName(){
    List<Users> list = this.usersDao.selectUserByName("张三");for (Users users : list) {
    System.out.println(users);}}/*** SQL测试*/@Test@Transactionalpublic void testSelectUserByNameUseSQL(){
    List<Users> list = this.usersDao.selectUserByNameUseSQL("张三");for (Users users : list) {
    System.out.println(users);}}/*** Criteria测试*/@Test@Transactionalpublic void testSelectUserByNameUseCriteria(){
    List<Users> list = this.usersDao.selectUserByNameUseCriteria("张三");for (Users users : list) {
    System.out.println(users);}}
}

在这里插入图片描述

注意:本文是在上一篇文章的基础上整合的hibernateJPA,所以很多描述就省略掉了~

  相关解决方案