一、基本Demo

1 前置准备

1.1 需求

使⽤ Spring Data JPA 完成对 tb_resume 表(简历表)的Dao 层操作(增删改查,排序,分⻚等)

1.2 数据表设计

Spring整合 - 图21.3 初始化Sql语句

  1. SET NAMES utf8mb4;
  2. SET FOREIGN_KEY_CHECKS = 0;
  3. -- Table structure for tb_resume
  4. DROP TABLE IF EXISTS `tb_resume`;
  5. CREATE TABLE `tb_resume` (
  6. `id` bigint(20) NOT NULL AUTO_INCREMENT,
  7. `address` varchar(255) DEFAULT NULL,
  8. `name` varchar(255) DEFAULT NULL,
  9. `phone` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`)
  10. ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
  11. -- Records of tb_resume
  12. BEGIN;
  13. INSERT INTO `tb_resume` VALUES (1, '北京', '张三', '131000000');
  14. INSERT INTO `tb_resume` VALUES (2, '上海', '李四', '151000000');
  15. INSERT INTO `tb_resume` VALUES (3, '⼴州', '王五', '153000000'); COMMIT;
  16. SET FOREIGN_KEY_CHECKS = 1;

1.4 构建⼯程

  • 创建⼯程导⼊坐标(Java框架于我们⽽⾔就是⼀堆jar)
  • 配置 Spring 的配置⽂件(配置指定框架执⾏的细节)
  • 编写实体类 Resume,使⽤ JPA 注解配置映射关系
  • 编写⼀个符合 Spring Data JPA 的 Dao 层接⼝(ResumeDao接⼝)
  • 操作 ResumeDao 接⼝对象完成 Dao 层开发

    2 导⼊坐标

    创建普通maven工程
    image.png ```xml junit junit 4.12 test
org.springframework.data spring-data-jpa 2.1.8.RELEASE javax.el javax.el-api 3.0.1-b04 org.glassfish.web javax.el 2.2.6 org.springframework spring-aop 5.1.12.RELEASE org.aspectj aspectjweaver 1.8.13 org.springframework spring-context 5.1.12.RELEASE org.springframework spring-context-support 5.1.12.RELEASE org.springframework spring-tx 5.1.12.RELEASE

org.springframework spring-orm 5.1.12.RELEASE org.springframework spring-beans 5.1.12.RELEASE org.springframework spring-core 5.1.12.RELEASE

org.hibernate hibernate-core 5.4.0.Final org.hibernate hibernate-entitymanager 5.4.0.Final org.hibernate hibernate-validator 5.4.0.Final

mysql mysql-connector-java 5.1.46 com.alibaba druid 1.1.21 org.springframework spring-test 5.1.12.RELEASE

spring-data-jpa依赖已经直接引入了spring相关依赖,spring依赖无需重复引入。
<a name="ceNv0"></a>
## 3 配置 Spring 的配置⽂件
```xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/data/jpa
        https://www.springframework.org/schema/data/jpa/spring-jpa.xsd
">

    <!--对Spring和SpringDataJPA进行配置-->

    <!--1、创建数据库连接池druid-->
    <!--引入外部资源文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!--第三方jar中的bean定义在xml中-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!--2、配置一个JPA中非常重要的对象,entityManagerFactory
            entityManager类似于mybatis中的SqlSession
            entityManagerFactory类似于Mybatis中的SqlSessionFactory
    -->
    <bean id="entityManagerFactory"
          class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <!--配置一些细节.......-->

        <!--配置数据源-->
        <property name="dataSource" ref="dataSource"/>
        <!--配置包扫描(pojo实体类所在的包)-->
        <property name="packagesToScan" value="com.hua.jpa.pojo"/>
        <!--指定jpa的具体实现,也就是hibernate-->
        <property name="persistenceProvider">
            <bean class="org.hibernate.jpa.HibernatePersistenceProvider"></bean>
        </property>
        <!--jpa方言配置,不同的jpa实现对于类似于beginTransaction等细节实现起来是不一样的,
               所以传入JpaDialect具体的实现类-->
        <property name="jpaDialect">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"></bean>
        </property>


        <!--配置具体provider,hibearnte框架的执行细节-->
        <property name="jpaVendorAdapter" >
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <!--定义hibernate框架的一些细节-->

                <!--
                    配置数据表是否自动创建
                    因为我们会建立pojo和数据表之间的映射关系
                    程序启动时,如果数据表还没有创建,是否要程序给创建一下
                -->
                <property name="generateDdl" value="false"/>

                <!--
                    指定数据库的类型
                    hibernate本身是个dao层框架,可以支持多种数据库类型的,这里就指定本次使用的什么数据库
                -->
                <property name="database" value="MYSQL"/>

                <!--
                    配置数据库的方言
                    hiberante可以帮助我们拼装sql语句,但是不同的数据库sql语法是不同的,所以需要我们注入具体的数据库方言
                -->
                <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/>
                <!--是否显示sql
                    操作数据库时,是否打印sql
                -->
                <property name="showSql" value="true"/>

            </bean>
        </property>
    </bean>


    <!--3、引用上面创建的entityManagerFactory
             <jpa:repositories> 配置jpa的dao层细节
             base-package:指定dao层接口所在包
    -->
    <jpa:repositories base-package="com.hua.jpa.dao"
                      entity-manager-factory-ref="entityManagerFactory"
                      transaction-manager-ref="transactionManager"/>


    <!--4、事务管理器配置
        jdbcTemplate/mybatis 使用的是DataSourceTransactionManager
        jpa规范:JpaTransactionManager
    -->
    <bean id="transactionManager"
          class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>


    <!--5、声明式事务配置-->
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <!--6、配置spring包扫描-->
    <context:component-scan base-package="com.hua.jpa"/>

</beans>

4 编写实体类 Resume

使用JPA注解配置映射关系

import javax.persistence.*;

/**
 * 简历实体类(在类中要使用注解建立实体类和数据表之间的映射关系以及属性和字段的映射关系)
 * 1、实体类和数据表映射关系
 * @Entity
 * @Table
 * 2、实体类属性和表字段的映射关系
 * @Id 标识主键
 * @GeneratedValue 标识主键的生成策略
 * @Column 建立属性和字段映射
 */
@Entity
@Table(name = "tb_resume")
public class Resume {

    @Id
    /**
     * 生成策略经常使用的两种:
     * GenerationType.IDENTITY:依赖数据库中主键自增功能  Mysql
     * GenerationType.SEQUENCE:依靠序列来产生主键     Oracle
     */
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;
    @Column(name = "name")
    private String name;
    @Column(name = "address")
    private String address;
    @Column(name = "phone")
    private String phone;

    // 省略了set/get方法
}

5 编写 ResumeDao 接⼝

package com.hua.jpa.dao;

import com.hua.jpa.pojo.Resume;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;



/**
 * 一个符合SpringDataJpa要求的Dao层接口是需要继承JpaRepository和JpaSpecificationExecutor
 *
 * JpaRepository<操作的实体类类型,主键类型>
 *      封装了基本的CRUD操作
 *
 * JpaSpecificationExecutor<操作的实体类类型>
 *      封装了复杂的查询(分页、排序等)
 *
 */
public interface ResumeDao 
        extends JpaRepository<Resume,Long>, JpaSpecificationExecutor<Resume> {


}

6 编写ResumeService类

ResumeService接口

public interface ResumeService {

    public Resume updateOne(Resume resume);
}

ResumeServiceImpl

package com.hua.jpa.service.impl;

import com.hua.jpa.dao.ResumeDao;
import com.hua.jpa.pojo.Resume;
import com.hua.jpa.service.ResumeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * @program: springmvc
 * @description: 简历业务实现类
 * @author: HUA
 * @create: 2022-05-04 16:24
 **/
@Service
public class ResumeServiceImpl implements ResumeService {

    @Autowired
    private ResumeDao resumeDao;

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Resume updateOne(Resume resume) {
        Resume resume1 = resumeDao.save(resume);
        int i = 1/0;
        return resume1;
    }
}

6 测试代码

6.1 测试dao接口

操作 ResumeDao 接⼝完成 Dao 层开发(客户端测试)

package com.hua.jpa.test;

import com.hua.jpa.dao.ResumeDao;
import com.hua.jpa.pojo.Resume;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.Optional;

/**
 * @program: springmvc
 * @description:
 * @author: HUA
 * @create: 2022-05-04 16:14
 **/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class ResumeDaoTest {


    // 要测试IOC哪个对象注入即可
    @Autowired
    private ResumeDao resumeDao;

    @Test
    public void testFindById() {
        // 早期的版本 dao.findOne(id);

        /*
            select resume0_.id as id1_0_0_,
                resume0_.address as address2_0_0_, resume0_.name as name3_0_0_,
                 resume0_.phone as phone4_0_0_ from tb_resume resume0_ where 
                 resume0_.id=?
         */

        Optional<Resume> optional = resumeDao.findById(1l);
        Resume resume = optional.get();
        System.out.println(resume);
    }


    @Test
    public void testFindOne() {
        Resume resume = new Resume();
        resume.setId(1l);
        resume.setName("张三");
        Example<Resume> example = Example.of(resume);
        Optional<Resume> one = resumeDao.findOne(example);
        Resume resume1 = one.get();
        System.out.println(resume1);
    }


    @Test
    public void testSave() {
        // 新增和更新都使用save方法,通过传入的对象的主键有无来区分,
        // 没有主键信息那就是新增,有主键信息就是更新
        Resume resume = new Resume();
        resume.setId(5l);
        resume.setName("赵六");
        resume.setAddress("成都");
        resume.setPhone("132000000");
        Resume save = resumeDao.save(resume);
        System.out.println(save);
    }

    @Test
    public void testDelete(){
        resumeDao.deleteById(5l);
    }

}

6.2 测试service接口

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class ResumeServiceTest {

    @Autowired
    private ResumeService resumeService;

    @Test
    public void test1() {
        Resume resume = new Resume();
        resume.setId(5l);
        resume.setName("赵六2");
        resume.setAddress("成都");
        resume.setPhone("132000000");
        Resume save = resumeService.updateOne(resume);
        System.out.println(save);
    }
}
  • 注释掉实现类异常代码,运行成功。
  • 开启异常代码,数据库无脏数据。