Spring整合HibernateJPA

2022-12-01 22:51:01 浏览数 (1)

Spring整合HibernateJPA

现如今的ORM框架还是比较多的比如Hibernate,TopLink以及OpenJPA等等,为了简化ORM框架的使用,JPA随之产生。

  JPA是Java Persistence API的简称,中文名Java持久层API,由 Sun 公司提供了一对对于持久层操作的标准(接口 文档),说白了就是在各种ORM框架之上封装了一套API实现统一操作。同时又依赖各种ORM框架去实现。hibernate3.2版本后提供了对JPA的实现。

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-entitymanager</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. 添加相关的配置文件

代码语言:javascript复制
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/logistics?characterEncoding=utf-8&serverTimezone=UTC
jdbc.username=root
jdbc.password=123456

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/tx/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.jpa.LocalContainerEntityManagerFactoryBean" id="sessionFactory">
        <!-- 关联数据源 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 配置Hibernate的属性信息 -->
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="database" value="MYSQL"/>
                <property name="generateDdl" value="true"/>
                <property name="showSql" value="true"/>
            </bean>
            <!--<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>
​
​
    <!--  配置事务管理-->
    <bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
        <property name="entityManagerFactory" ref="sessionFactory" />
    </bean>
​
    <!-- 配置开启事务注解 -->
    <tx:annotation-driven transaction-manager="transactionManager" />
​
    <!-- 配置扫描路径 -->
    <context:component-scan base-package="com.bobo" />
</beans>

4. 创建POJO

代码语言: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;
    }
​
    @Override
    public String toString() {
        return "Users{"  
                "userId="   userId  
                ", userName='"   userName   '''  
                ", 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 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 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;
​
​
@Repository
public class UserDaoImpl implements IUserDao {
​
​
    @PersistenceContext(name = "entityManagerFactory")
    private EntityManager manager;
​
    @Override
    public void insertUsers(Users users) {
        manager.persist(users);
    }
​
    @Override
    public void updateUsers(Users users) {
        manager.merge(users);
    }
​
    @Override
    public void deleteUsers(Users users) {
        users = this.selectUsersById(users.getUserId());
        manager.remove(users);
    }
​
    @Override
    public Users selectUsersById(Integer userId) {
        return manager.find(Users.class,userId);
    }
​
    @Override
    public List<Users> selectUsersByName(String userName) {
        return manager.createQuery(" from Users where userName = :abc")
                .setParameter("abc",userName)
                .getResultList();
    }
​
    @Override
    public List<Users> selectUsersByNameUseSQL(String userName) {
        return manager.createNativeQuery("select * from t_user where user_name = ?",Users.class)
                .setParameter(1,userName)
                .getResultList();
    }
​
    @Override
    public List<Users> selectUsersByNameUseCriteria(String userName) {
​
        CriteriaBuilder builder = manager.getCriteriaBuilder();
        CriteriaQuery<Users> query = builder.createQuery(Users.class);
        Root<Users> root = query.from(Users.class);
        Predicate cate = builder.equal(root.get("userName"), userName);
        query.where(cate);
        TypedQuery<Users> typedQuery = manager.createQuery(query);
        return typedQuery.getResultList();
    }
}
​

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("Mic");
        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);
        }
    }
​
​
}
​

0 人点赞