Spring Data JPA(四)—— SpringDataJpa入门

2020-04-02

一、Spring Data JPA概述

1.1 Spring Data JPA简介

Spring Data’s mission is to provide a familiar and consistent, Spring-based programming model for data access while still retaining the special traits of the underlying data store.

It makes it easy to use data access technologies, relational and non-relational databases, map-reduce frameworks, and cloud-based data services. This is an umbrella project which contains many subprojects that are specific to a given database. The projects are developed by working together with many of the companies and developers that are behind these exciting technologies.

  • Spring Data JPA是Spring基于ORM框架、JPA规范的基础上封装的一套JPA应用框架,可使开发者用极简的代码即可实现对数据库的访问和操作。它提供了包括增删改查等在内的常用功能,且易于扩展。
  • Spring Data JPA让开发者解脱了DAO层的操作,基本上所有CRUD都可以依赖于它来实现,在实际的工作过程中,推荐使用Spring Data JPA+ORM(如:Hibernate)完成操作,这样在切换不同的ORM框架时提供了极大的方便,同时也使数据库操作更加简单,方便解耦。

1.2 Spring Data JPA的特性

Features

  • Powerful repository and custom object-mapping abstractions
  • Dynamic query derivation from repository method names
  • Implementation domain base classes providing basic properties
  • Support for transparent auditing (created, last changed)
  • Possibility to integrate custom repository code
  • Easy Spring integration via JavaConfig and custom XML namespaces
  • Advanced integration with Spring MVC controllers
  • Experimental support for cross-store persistence
  • Spring Data JPA极大地简化了数据库访问层代码,使用后开发者只需在dao层中写接口,就自动具有了增删改查、分页查询等方法。

1.3 Spring Data JPA与JPA和Hibernate的关系

image.png

  • JPA是一套规范,内部是由接口和抽象类组成的。Hibernate是一套成熟的ORM框架,而且Hibernate实现了JPA规范,所以也可以称Hibernate为JPA的一种实现方式,我们使用JPA的API编程,意味着站在更高的角度上看待问题(面向接口编程)。
  • Spring Data JPA是Spring提供的一套对JPA操作更加高级的封装,是在JPA规范下的数据持久化的解决方案。

二、Spring Data JPA快速入门

2.1 搭建环境

  1. 创建工程导入依赖
    <properties>
        <spring.version>5.2.5.RELEASE</spring.version>
        <hibernate.version>5.4.13.Final</hibernate.version>
        <slf4j.version>1.7.30</slf4j.version>
        <log4j.version>1.2.17</log4j.version>
        <c3p0.version>0.9.1.2</c3p0.version>
        <mysql.version>8.0.19</mysql.version>
    </properties>
    
    <dependencies>
        <!-- junit单元测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    
        <!-- spring beg -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.5</version>
        </dependency>
    
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
    
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
    
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>
    
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>
    
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
    
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
    
        <!-- spring end -->
    
        <!-- hibernate beg -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>6.1.2.Final</version>
            <exclusions>
                <exclusion>
                    <artifactId>classmate</artifactId>
                    <groupId>com.fasterxml</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- hibernate end -->
    
        <!-- c3p0 beg -->
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>${c3p0.version}</version>
        </dependency>
        <!-- c3p0 end -->
    
        <!-- log end -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>
    
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
    
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <!-- log end -->
    
    
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
    
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>2.2.6.RELEASE</version>
            <exclusions>
                <exclusion>
                    <artifactId>slf4j-api</artifactId>
                    <groupId>org.slf4j</groupId>
                </exclusion>
            </exclusions>
        </dependency>
    
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
    
        <!-- el beg 使用spring data jpa 必须引入 -->
        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>javax.el-api</artifactId>
            <version>3.0.0</version>
        </dependency>
    
        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>javax.el</artifactId>
            <version>2.2.6</version>
            <exclusions>
                <exclusion>
                    <artifactId>javax.el-api</artifactId>
                    <groupId>javax.el</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- el end -->
    </dependencies>
    
  2. 编写spring配置文件 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:jpa="http://www.springframework.org/schema/data/jpa"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/data/jpa https://www.springframework.org/schema/data/jpa/spring-jpa.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    
        <!-- Spring和Spring Data JPA的配置 -->
    
        <!-- 1.创建EntityManagerFactory对象交给Spring容器管理 -->
        <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <!-- 扫描实体类所在包 -->
            <property name="packagesToScan" value="com.cherishvii.domain"/>
            <!-- JPA的实现方式 -->
            <property name="persistenceProvider">
                <bean class="org.hibernate.jpa.HibernatePersistenceProvider"/>
            </property>
            <!-- JPA的供应商适配器 -->
            <property name="jpaVendorAdapter">
                <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                    <!-- 指定数据库类型 -->
                    <property name="database" value="MYSQL"/>
                    <!-- 是否自动创建表 -->
                    <property name="generateDdl" value="false"/>
                    <!-- 数据库方言 -->
                    <property name="databasePlatform" value="org.hibernate.dialect.MySQL8Dialect"/>
                    <property name="showSql" value="true"/>
                </bean>
            </property>
            <!-- JPA的方言:高级特性 -->
            <property name="jpaDialect">
                <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
            </property>
        </bean>
    
        <!-- 2.创建数据库连接池 -->
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="user" value=""/>
            <property name="password" value=""/>
            <property name="jdbcUrl" value=""/>
            <property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
        </bean>
    
        <!-- 3.整合Spring Data JPA -->
        <jpa:repositories base-package="com.cherishvii.dao" transaction-manager-ref="transactionManager" entity-manager-factory-ref="entityManagerFactory"/>
    
        <!-- 4.配置事务管理器 -->
        <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
            <property name="dataSource" ref="dataSource"/>
            <property name="entityManagerFactory" ref="entityManagerFactory"/>
        </bean>
    
        <!-- 5.声明式事务(本示例无service层,忽略) -->
    
        <!-- 6.配置包扫描 -->
        <context:component-scan base-package="com.cherishvii"/>
    </beans>
    
  3. 编写实体类,使用JPA注解配置映射关系
    package com.cherishvii.domain;
    
    import javax.persistence.*;
    
    /**
     * 1.实体类和表的映射关系
     * 2.类中属性和表中字段的映射关系
     *
     * @author CHERISHVII
     * @author www.cherishvii.com
     * @version V1.0
     * @date 2020/4/2 10:04
     */
    @Entity
    @Table(name = "tab_customer")
    public class Customer {
    
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "cust_id")
        private Long custId;
        @Column(name = "cust_address")
        private String custAddress;
        @Column(name = "cust_industry")
        private String custIndustry;
        @Column(name = "cust_level")
        private String custLevel;
        @Column(name = "cust_name")
        private String custName;
        @Column(name = "cust_phone")
        private String custPhone;
        @Column(name = "cust_source")
        private String custSource;
    
        public Long getCustId() {
            return custId;
        }
    
        public void setCustId(Long custId) {
            this.custId = custId;
        }
    
        public String getCustAddress() {
            return custAddress;
        }
    
        public void setCustAddress(String custAddress) {
            this.custAddress = custAddress;
        }
    
        public String getCustIndustry() {
            return custIndustry;
        }
    
        public void setCustIndustry(String custIndustry) {
            this.custIndustry = custIndustry;
        }
    
        public String getCustLevel() {
            return custLevel;
        }
    
        public void setCustLevel(String custLevel) {
            this.custLevel = custLevel;
        }
    
        public String getCustName() {
            return custName;
        }
    
        public void setCustName(String custName) {
            this.custName = custName;
        }
    
        public String getCustPhone() {
            return custPhone;
        }
    
        public void setCustPhone(String custPhone) {
            this.custPhone = custPhone;
        }
    
        public String getCustSource() {
            return custSource;
        }
    
        public void setCustSource(String custSource) {
            this.custSource = custSource;
        }
    
        @Override
        public String toString() {
            return "Customer{" +
                    "custId=" + custId +
                    ", custAddress='" + custAddress + '\'' +
                    ", custIndustry='" + custIndustry + '\'' +
                    ", custLevel='" + custLevel + '\'' +
                    ", custName='" + custName + '\'' +
                    ", custPhone='" + custPhone + '\'' +
                    ", custSource='" + custSource + '\'' +
                    '}';
        }
    }
    

2.2 编写一个符合Spring Data JPA的dao层接口

  • 只需要编写dao层接口,不需要编写实现类

  • dao层接口规范

    1. 需要继承两个接口(JpaRepository,JpaSpecificationExecutor)
      • JpaRepository<操作的实体类类型,实体类中主键的类型>
        • 封装了基本CRUD操作
      • JpaSpecifictionExecutor<操作的实体类类型>
        • 封装了复杂查询(分页等)
    2. 需要提供相应的泛型
    package com.cherishvii.dao;
    
    import com.cherishvii.domain.Customer;
    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
    
    /**
     * 符合Spring Data JPA的dao层接口规范
     * JpaRepository<操作的实体类型,实体类中主键的类型>
     * 封装了基本CRUD操作
     * JpaSpecificationExecutor<操作的实体类型>
     * 封装了复杂查询(分页等)
     */
    public interface ICustomerDao extends JpaRepository<Customer, Long>, JpaSpecificationExecutor<Customer> {
    
    }
    

2.3 编写测试类

  • findById(id):查询
  • save(Entity):有id为更新,没有id为保存
  • deleteById(id):删除
  • findAll():查询全部
    package com.cherishvii.test;
    
    import com.cherishvii.dao.ICustomerDao;
    import com.cherishvii.domain.Customer;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    import java.util.List;
    import java.util.Optional;
    
    /**
     * @author CHERISHVII
     * @author www.cherishvii.com
     * @version V1.0
     * @date 2020/4/2 10:24
     */
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("classpath:applicationContext.xml")
    public class CustomerDaoTest {
    
        @Autowired
        private ICustomerDao customerDao;
    
        /**
         * 根据Id查询
         */
        @Test
        public void testFindById() {
            Customer customer = customerDao.findById(3l).orElse(null);
            System.out.println(customer);
        }
    
        /**
         * save:保存或者更新
         * 如果不存在主键id:保存
         * 如果存在主键id:根据id查询,再更新
         */
        @Test
        public void testSave() {
            Customer customer = new Customer();
            customer.setCustName("test3");
            customer.setCustIndustry("IT");
            customer.setCustLevel("common");
            customerDao.save(customer);
        }
    
        /**
         * 更新操作
         */
        @Test
        public void testUpdate() {
            Customer customer = customerDao.findById(6l).orElse(null);
            customer.setCustLevel("vip");
            customerDao.save(customer);
        }
    
        /**
         * 删除操作
         */
        @Test
        public void testRemove() {
            customerDao.deleteById(6l);
        }
    
        /**
         * 查询所有
         */
        @Test
        public void testFindAll() {
            List<Customer> customerList = customerDao.findAll();
            for (Customer customer : customerList) {
                System.out.println(customer);
            }
        }
    }
    

标题:Spring Data JPA(四)—— SpringDataJpa入门
作者:CherishVII
地址:https://cherishvii.com/articles/2020/04/02/1585799327617.html

评论
发表评论