SpringDataJPA

Posted zddsl

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringDataJPA相关的知识,希望对你有一定的参考价值。

ORM思想

  ORM 即 Object-Relational Mapping,对象关系映射。简单来说就是通过操作对应的实体类来操作表的思想。

  实现了ORM思想的框架:hibernate 等

 

JPA概述

  JPA的全称是Java Persistence API, 即Java 持久化API。JPA是一种基于orm思想的规范,是由接口和抽象类组成的;

 

SpringDataJpa

 

  1.SpringDataJpa与 Jpa 和 hibernate 的关系:

      SpringDataJpa只是jpa规范的进一步封装,底层也需要hibernate等框架的实现

 

  2.SpringDataJpa入门:

      (1) 引入依赖

      技术图片
<properties>
        <spring.version>4.2.4.RELEASE</spring.version>
        <hibernate.version>5.0.7.Final</hibernate.version>
        <slf4j.version>1.6.6</slf4j.version>
        <log4j.version>1.2.12</log4j.version>
        <c3p0.version>0.9.1.2</c3p0.version>
        <mysql.version>5.1.6</mysql.version>
    </properties>

    <dependencies>
        <!-- junit单元测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.9</version>
            <scope>test</scope>
        </dependency>

        <!-- spring beg -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.8</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>5.2.1.Final</version>
        </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>1.9.0.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>

        <!-- el beg 使用spring data jpa 必须引入 -->
        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>javax.el-api</artifactId>
            <version>2.2.4</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>javax.el</artifactId>
            <version>2.2.4</version>
        </dependency>
        <!-- el end -->
    </dependencies>
SpringDataJpa入门程序依赖

 

      (2) SpringDataJpa与Spring整合的配置文件

      技术图片
<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/data/jpa
        http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

    <!-- 1.dataSource 配置数据库连接池-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/jpa" />
        <property name="user" value="root" />
        <property name="password" value="root" />
    </bean>

    <!-- 2.配置entityManagerFactory -->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="com.myjava.jpa.entity" />

        <!--JPA的供应商适配器-->
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="generateDdl" value="false" />
                <property name="database" value="MYSQL" />
                <property name="showSql" value="true" />
            </bean>
        </property>

    </bean>


    <!-- 3.事务管理器-->
    <!-- JPA事务管理器  -->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <!--txAdvice-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <!--aop-->
    <aop:config>
        <aop:pointcut id="pointcut" expression="execution(* com.myjava.jpa.service.*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" />
    </aop:config>

    <!--4.dao包扫描器-->
    <jpa:repositories base-package="com.myjava.jpa.dao"
                      transaction-manager-ref="transactionManager"
                      entity-manager-factory-ref="entityManagerFactory"></jpa:repositories>

</beans>
SpringDataJpa与Spring整合的配置文件

      

      (3) 编写实体类和数据库表的映射配置

 

      技术图片
//声明实体类
@Entity
//建立实体类和表的映射关系
@Table(name = "cust")
public class Customer implements Serializable{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "cust_id")
    private Long id;
    @Column(name = "cust_name")
    private String name;
    @Column(name = "cust_industry")
    private String industry;
    @Column(name = "cust_level")
    private String level;
    @Column(name = "cust_addressdress")
    private String addressdress;


    //标注一对一关联关系
    @OneToOne(cascade = CascadeType.ALL)
    //标注外键关联
    //name:标注表中存储外键字段的字段名称
    @JoinColumn(name = "ext_Id")
    //也可以主键关联,但是关联的类里面也要加上这个注解
    //@PrimaryKeyJoinColumn
    private CustomerExt ext;



    @Override
    public String toString() {
        return "Customer{" +
                "id=" + id +
                ", name=‘" + name + ‘‘‘ +
                ", industry=‘" + industry + ‘‘‘ +
                ", level=‘" + level + ‘‘‘ +
                ", addressdress=‘" + addressdress + ‘‘‘ +
                ‘}‘;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getIndustry() {
        return industry;
    }

    public void setIndustry(String industry) {
        this.industry = industry;
    }

    public String getLevel() {
        return level;
    }

    public void setLevel(String level) {
        this.level = level;
    }

    public String getAddressdress() {
        return addressdress;
    }

    public void setAddressdress(String addressdress) {
        this.addressdress = addressdress;
    }

    public CustomerExt getExt() {
        return ext;
    }

    public void setExt(CustomerExt ext) {
        this.ext = ext;
    }
}
配置实体类和表的映射关系

 

      (4) 按照框架规范提供dao接口

      技术图片
//泛型右边参数是主键类型
public interface CustomerDao extends JpaRepository<Customer,Long> {

}
按照框架规范提供dao接口

 

      (5)基本的CURD操作

        1.增:save

        2.删:delete

        3.改:先查出来,然后save

        4.查:findOne,findAll,getOne(这个方法是懒加载)

      

      (6)更加灵活的查询方法

        基本的查询方法不够灵活时的其他方法(比如不能通过其他属性查询)

          ①命名规则查询

            按照Spring Data JPA 定义的规则,查询方法以findBy开头

          ②JPQL语句查询

            在dao中定义一个方法,加上@Query注解,在注解中输入JPQL语句即可

            例如:@Query(value="from Customer")

          ③原生sql语句

            在@Query注解中输入sql语句,加个 nativeQuery = true 即可

 

    

  3.SpringDataJpa与表关系

 

      (1) 一对一

        外键关联

          外键保存的表对应的类中应该加@OneToOne注解,@JoinColumn注解

           技术图片
package com.myjava.jpa.entity;

import javax.persistence.*;
import java.io.Serializable;

//声明实体类
@Entity
//建立实体类和表的映射关系
@Table(name = "cust")
public class Customer implements Serializable{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "cust_id")
    private Long id;
    @Column(name = "cust_name")
    private String name;
    @Column(name = "cust_industry")
    private String industry;
    @Column(name = "cust_level")
    private String level;
    @Column(name = "cust_addressdress")
    private String addressdress;


    //标注一对一关联关系
    @OneToOne(cascade = CascadeType.ALL)
    //标注外键关联
    //name:标注表中存储外键字段的字段名称
    @JoinColumn(name = "ext_Id")
    //也可以主键关联,但是关联的类里面也要加上这个注解
    //@PrimaryKeyJoinColumn
    private CustomerExt ext;

    //get set方法
    
}
例子

 

      (2) 一对多

          一的一方只用加入加入@OneToMany注解,多的一方要加入 @ManyToOne注解 和 @JoinColumn注解

           技术图片
@Entity
@Table(name = "master")
public class Master {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "master_id")
    private Long masterId;
    private String name;
    private Integer age;
    private String info;

    //fetch:默认是延迟加载LAZY
    @OneToMany(cascade = CascadeType.ALL,mappedBy = "master",fetch = FetchType.EAGER)
    private Set<Servant> servants = new HashSet<Servant>();
}
一的一方

      

           技术图片
@Entity
@Table(name = "servant")
public class Servant {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "servant_id")
    private Long servantId;
    private String name;
    private String ability;
    private String profession;

    @ManyToOne
    @JoinColumn(name = "mas_id")
    private Master master;
多的一方

 

 

      (3) 多对多

          两方都使用@ManyToMany注解,一方要加入@JoinTable标签创建中间表

          @JoinTable标签有3个重要的参数

              ① name:中间表表名

              ② joinColumn:当前表映射在中间表的列

              ③ inverseJoinColumns:另一个类的列映射在中间表的名称

 

           技术图片
@Entity
@Table(name = "sys_user")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "uid")
    private Long id;
    private String username;
    private String password;

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(
            name = "user_role",
            joinColumns = @JoinColumn(name = "user_id"),
            inverseJoinColumns = @JoinColumn(name = "role_id")
    )
例子

 

以上是关于SpringDataJPA的主要内容,如果未能解决你的问题,请参考以下文章

SpringDataJpa

SpringBoot实战SpringDataJPA

SpringDataJpa

基于springboot+thymeleaf+springDataJpa自带的分页插件实现完整的动态分页

Spring Data JPA入门

15 Spring Data JPA概述