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.RELEASEspring.version>
        <hibernate.version>5.0.7.Finalhibernate.version>
        <slf4j.version>1.6.6slf4j.version>
        <log4j.version>1.2.12log4j.version>
        <c3p0.version>0.9.1.2c3p0.version>
        <mysql.version>5.1.6mysql.version>
    properties>

    <dependencies>
        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.9version>
            <scope>testscope>
        dependency>

        
        <dependency>
            <groupId>org.aspectjgroupId>
            <artifactId>aspectjweaverartifactId>
            <version>1.6.8version>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-aopartifactId>
            <version>${spring.version}version>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>${spring.version}version>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-context-supportartifactId>
            <version>${spring.version}version>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-ormartifactId>
            <version>${spring.version}version>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-beansartifactId>
            <version>${spring.version}version>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-coreartifactId>
            <version>${spring.version}version>
        dependency>

        

        
        <dependency>
            <groupId>org.hibernategroupId>
            <artifactId>hibernate-coreartifactId>
            <version>${hibernate.version}version>
        dependency>
        <dependency>
            <groupId>org.hibernategroupId>
            <artifactId>hibernate-entitymanagerartifactId>
            <version>${hibernate.version}version>
        dependency>
        <dependency>
            <groupId>org.hibernategroupId>
            <artifactId>hibernate-validatorartifactId>
            <version>5.2.1.Finalversion>
        dependency>
        

        
        <dependency>
            <groupId>c3p0groupId>
            <artifactId>c3p0artifactId>
            <version>${c3p0.version}version>
        dependency>
        

        
        <dependency>
            <groupId>log4jgroupId>
            <artifactId>log4jartifactId>
            <version>${log4j.version}version>
        dependency>

        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-apiartifactId>
            <version>${slf4j.version}version>
        dependency>

        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-log4j12artifactId>
            <version>${slf4j.version}version>
        dependency>
        


        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>${mysql.version}version>
        dependency>

        <dependency>
            <groupId>org.springframework.datagroupId>
            <artifactId>spring-data-jpaartifactId>
            <version>1.9.0.RELEASEversion>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-testartifactId>
            <version>4.2.4.RELEASEversion>
        dependency>

        
        <dependency>
            <groupId>javax.elgroupId>
            <artifactId>javax.el-apiartifactId>
            <version>2.2.4version>
        dependency>

        <dependency>
            <groupId>org.glassfish.webgroupId>
            <artifactId>javax.elartifactId>
            <version>2.2.4version>
        dependency>
        
    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">

    
    <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>

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

        
        <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>


    
    
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    bean>

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

    
    <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 {

}
按照框架规范提供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 servants = new HashSet();
}
一的一方

      

           
@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")
    )
    private Set roleSet  = new HashSet();

    public Set getRoleSet() {
        return roleSet;
    }

    public void setRoleSet(Set roleSet) {
        this.roleSet = roleSet;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }

    public Long getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
例子

 

你可能感兴趣的:(SpringDataJPA)