【Spring Data JPA】SpringDataJPA上手教程

目錄

一 SpringDataJPA概述

二 SpringDataJPA快速入門

2.1需求說明

2.2 搭建SpringDataJPA開發環境

2.3 使用Spring Data JPA完成需求

三 SpringDataJPA的運行過程及原理簡析

3.1 Spring Data JPA 的常用接口分析

3.2 Spring Data JPA的實現過程

3.3 Spring Data JPA完整的調用過程分析

四 SpringDataJPA的查詢方式

4.1 使用Spring Data JPA 中接口定義的方法進行查詢

4.2 使用JPQL的方式查詢

4.3 使用SQL語句查詢

4.4 方法命名規則查詢

五 Specifications動態查詢

5.1    使用Specifications完成條件查詢

5.2    基於Specifications的分頁查詢

5.3    方法對應關係

六 多表之間的關係和操作多表的操作步驟

6.1 數據庫中多表存在着三種關係

6.2 表關係分析步驟

七 完成多表操作

7.1 一對多

7.2 多對多

八 導航查詢


一 SpringDataJPA概述

SpringDataJPA是Spring基於ORM框架、JPA規範的基礎上封裝的一套JPA應用框架,可以簡化開發者們的操作,只需要在dao層寫接口,就自動具備了增刪改查、分頁查詢等方法。

SpringDataJPA和JPA和Hibernate之間的關係

JPA是一套規範,內部是由接口和抽象類組成的。Hibernate是一套成熟的ORM框架,Hibernate實現了JPA規範,是JPA的一種實現方式。

SpringDataJPA是Spring提供的一套對JPA操作更加高級的封裝,是JPA規範下專門用來進行數據持久化的解決方案。

 

二 SpringDataJPA快速入門

2.1需求說明

使用Spring Data JPA 完成客戶的基本CRUD操作

2.2 搭建SpringDataJPA開發環境

2.2.1 導入Spring Data JPA座標

創建Maven工程,使用Spring Data JPA,需要整合Spring與Spring Data JPA,並且需要提供JPA的服務提供者hibernate,所以需要導入spring相關座標,hibernate座標,數據庫驅動座標等。pom.xml添加如下依賴

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

2.2.2 整合SpringDataJPA與Spring

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: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="111111" />
	</bean>
	
	<!-- 2.配置entityManagerFactory -->
	<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="packagesToScan" value="com.bupt.entity" />
		<property name="persistenceProvider">
			<bean class="org.hibernate.jpa.HibernatePersistenceProvider" />
		</property>
		<!--JPA的供應商適配器-->
		<property name="jpaVendorAdapter">
			<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
				<property name="generateDdl" value="false" />
				<property name="database" value="MYSQL" />
				<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
				<property name="showSql" value="true" />
			</bean>
		</property>
		<property name="jpaDialect">
			<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
		</property>
	</bean>
    
	
	<!-- 3.事務管理器-->
	<!-- JPA事務管理器  -->
	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="entityManagerFactory" />
	</bean>
	
	<!-- 整合spring data jpa-->
	<jpa:repositories base-package="com.bupt.dao"
		transaction-manager-ref="transactionManager"
		entity-manager-factory-ref="entityManagerFactory"></jpa:repositories>
		
	<!-- 4.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>
	
	<!-- 5.aop-->
	<aop:config>
		<aop:pointcut id="pointcut" expression="execution(*com.bupt.service.*.*(..))" />
		<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" />
	</aop:config>
	
	<context:component-scan base-package="cn.itcast"></context:component-scan>
		
	<!--組裝其它 配置文件-->
	
</beans>

2.2.3 使用JPA註解配置映射關係

數據庫建表建表語句

DROP TABLE IF EXISTS `cst_customer`;
CREATE TABLE `cst_customer`  (
  `cust_id` bigint(20) NOT NULL AUTO_INCREMENT,
  `cust_address` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `cust_industry` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `cust_level` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `cust_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `cust_phone` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `cust_source` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`cust_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

創建實體類Customer對象,配置映射關係

package com.bupt.domain;


import javax.persistence.*;

@Entity //聲明實體類
@Table(name = "cst_customer") //建立實體類和表的映射關係
public class Customer {

    @Id//聲明當前私有屬性爲主鍵
    @GeneratedValue(strategy = GenerationType.IDENTITY) //配置主鍵的生成策略
    @Column(name = "cust_id") //指定和表中cust_id字段的映射關係
    private Long custId;

    @Column(name = "cust_name") //指定和表中cust_name字段的映射關係
    private String custName;

    @Column(name = "cust_source")//指定和表中cust_source字段的映射關係
    private String custSource;

    @Column(name = "cust_industry")//指定和表中cust_industry字段的映射關係
    private String custIndustry;

    @Column(name = "cust_level")//指定和表中cust_level字段的映射關係
    private String custLevel;

    @Column(name = "cust_address")//指定和表中cust_address字段的映射關係
    private String custAddress;

    @Column(name = "cust_phone")//指定和表中cust_phone字段的映射關係
    private String custPhone;
    // 省略get set toString方法
}

2.3 使用Spring Data JPA完成需求

2.3.1 編寫符合SpringDataJPA規範的Dao層接口

在SpringDataJPA中,對於定義符合規範的Dao層接口,只需要遵循兩點:

  1. 創建一個dao層接口,並實現JpaRepository和JpaSpecificationExecutor
  2. 提供相應的泛型
package com.bupt.dao;

import com.bupt.domain.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

public interface CustomerDao extends JpaRepository<Customer, Long>, JpaSpecificationExecutor<Customer> {
    
}

 

2.3.2 完成基本CRUD操作

在test下進行測試

package com.bupt;


import com.bupt.dao.CustomerDao;
import com.bupt.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;

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

    @Autowired
    CustomerDao customerDao;


    /**
     * 保存客戶:調用save(obj)方法
     */
    @Test
    public void testSave() {
        Customer c = new Customer();
        c.setCustName("小破郵");
        customerDao.save(c);
    }

    /**
     * 修改客戶:調用save(obj)方法
     *      對於save方法的解釋:如果執行此方法是對象中存在id屬性,即爲更新操作會先根據id查詢,再更新
     *                      如果執行此方法中對象中不存在id屬性,即爲保存操作
     *
     */
    @Test
    public void testUpdate() {
        //根據id查詢id爲1的客戶
        Customer customer = customerDao.findOne(1l);
        //修改客戶名稱
        customer.setCustName("西土城路10號");
        //更新
        customerDao.save(customer);
    }

    /**
     * 根據id刪除:調用delete(id)方法
     */
    @Test
    public void testDelete() {
        customerDao.delete(1l);
    }

    /**
     * 根據id查詢:調用findOne(id)方法
     */
    @Test
    public void testFindById() {
        Customer customer = customerDao.findOne(2l);
        System.out.println(customer);
    }

}

三 SpringDataJPA的運行過程及原理簡析

3.1 Spring Data JPA 的常用接口分析

3.2 Spring Data JPA的實現過程

3.3 Spring Data JPA完整的調用過程分析

四 SpringDataJPA的查詢方式

4.1 使用Spring Data JPA 中接口定義的方法進行查詢

在繼承JpaRepository和JpaSpecificationExecutor後,就可以使用接口中定義的方法查詢

 

 

繼承JpaRepository後的方法列表繼承JpaSpecificationExecutor的方法列表

4.2 使用JPQL的方式查詢

使用Spring Data JPA提供的查詢方法已經可以解決大部分的應用場景,但是對於某些業務來說,我們還需要靈活的構造查詢條件,這時就可以使用@Query註解,結合JPQL的語句方式完成查詢

@Query 註解的使用非常簡單,只需在方法上面標註該註解,同時提供一個JPQL查詢語句即可

public interface CustomerDao extends JpaRepository<Customer, Long>,JpaSpecificationExecutor<Customer> {    
    //@Query 使用jpql的方式查詢。
    @Query(value="from Customer")
    public List<Customer> findAllCustomer();
    
    //@Query 使用jpql的方式查詢。?1代表參數的佔位符,其中1對應方法中的參數索引
    @Query(value="from Customer where custName = ?1")
    public Customer findCustomer(String custName);
}

此外,也可以通過使用 @Query 來執行一個更新操作,爲此,我們需要在使用 @Query 的同時,用 @Modifying 來將該操作標識爲修改查詢,這樣框架最終會生成一個更新的操作,而非查詢

  @Query(value="update Customer set custName = ?1 where custId = ?2")
    @Modifying
    public void updateCustomer(String custName,Long custId);

 

4.3 使用SQL語句查詢

Spring Data JPA同樣也支持sql語句的查詢,如下:

    /**
     * nativeQuery : 使用本地sql的方式查詢
     */
    @Query(value="select * from cst_customer",nativeQuery=true)
    public void findSql();

 

4.4 方法命名規則查詢

顧名思義,方法命名規則查詢就是根據方法的名字,就能創建查詢。只需要按照Spring Data JPA提供的方法命名規則定義方法的名稱,就可以完成查詢工作。Spring Data JPA在程序執行的時候會根據方法名稱進行解析,並自動生成查詢語句進行查詢。

按照Spring Data JPA 定義的規則,查詢方法以findBy開頭,涉及條件查詢時,條件的屬性用條件關鍵字連接,要注意的是:條件屬性首字母需大寫。框架在進行方法名解析時,會先把方法名多餘的前綴截取掉,然後對剩下部分進行解析。

  //方法命名方式查詢(根據客戶名稱查詢客戶)
    public Customer findByCustName(String custName);

具體的關鍵字,使用方法和生產成SQL如下表所示

Keyword

Sample

JPQL

And

findByLastnameAndFirstname

… where x.lastname = ?1 and x.firstname = ?2

Or

findByLastnameOrFirstname

… where x.lastname = ?1 or x.firstname = ?2

Is,Equals

findByFirstnameIs,

findByFirstnameEquals

… where x.firstname = ?1

Between

findByStartDateBetween

… where x.startDate between ?1 and ?2

LessThan

findByAgeLessThan

… where x.age < ?1

LessThanEqual

findByAgeLessThanEqual

… where x.age ⇐ ?1

GreaterThan

findByAgeGreaterThan

… where x.age > ?1

GreaterThanEqual

findByAgeGreaterThanEqual

… where x.age >= ?1

After

findByStartDateAfter

… where x.startDate > ?1

Before

findByStartDateBefore

… where x.startDate < ?1

IsNull

findByAgeIsNull

… where x.age is null

IsNotNull,NotNull

findByAge(Is)NotNull

… where x.age not null

Like

findByFirstnameLike

… where x.firstname like ?1

NotLike

findByFirstnameNotLike

… where x.firstname not like ?1

StartingWith

findByFirstnameStartingWith

… where x.firstname like ?1 (parameter bound with appended %)

EndingWith

findByFirstnameEndingWith

… where x.firstname like ?1 (parameter bound with prepended %)

Containing

findByFirstnameContaining

… where x.firstname like ?1 (parameter bound wrapped in %)

OrderBy

findByAgeOrderByLastnameDesc

… where x.age = ?1 order by x.lastname desc

Not

findByLastnameNot

… where x.lastname <> ?1

In

findByAgeIn(Collection ages)

… where x.age in ?1

NotIn

findByAgeNotIn(Collection age)

… where x.age not in ?1

TRUE

findByActiveTrue()

… where x.active = true

FALSE

findByActiveFalse()

… where x.active = false

IgnoreCase

findByFirstnameIgnoreCase

… where UPPER(x.firstame) = UPPER(?1)

五 Specifications動態查詢

JpaSpecificationExecutor 方法列表
	
		T findOne(Specification<T> spec);  //查詢單個對象

		List<T> findAll(Specification<T> spec);  //查詢列表

		//查詢全部,分頁
		//pageable:分頁參數
		//返回值:分頁pageBean(page:是springdatajpa提供的)
		Page<T> findAll(Specification<T> spec, Pageable pageable);

		//查詢列表
		//Sort:排序參數
		List<T> findAll(Specification<T> spec, Sort sort);

		long count(Specification<T> spec);//統計查詢
		
	* Specification :查詢條件
		自定義我們自己的Specification實現類
			實現
				//root:查詢的根對象(查詢的任何屬性都可以從根對象中獲取)
				//CriteriaQuery:頂層查詢對象,自定義查詢方式(瞭解:一般不用)
				//CriteriaBuilder:查詢的構造器,封裝了很多的查詢條件
				Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb); //封裝查詢條件
		

有時我們在查詢某個實體的時候,給定的條件是不固定的,這時就需要動態構建相應的查詢語句,在Spring Data JPA中可以通過JpaSpecificationExecutor接口查詢。相比JPQL,其優勢是類型安全,更加的面向對象。先看看JpaSpecificationExecutor接口有哪些方法

 public interface JpaSpecificationExecutor<T> {
   //根據條件查詢一個對象
    T findOne(Specification<T> spec);
   //根據條件查詢集合
    List<T> findAll(Specification<T> spec);
   //根據條件分頁查詢
    Page<T> findAll(Specification<T> spec, Pageable pageable);
   //排序查詢查詢
    List<T> findAll(Specification<T> spec, Sort sort);
   //統計查詢
    long count(Specification<T> spec);
}

對於JpaSpecificationExecutor,這個接口基本是圍繞着Specification接口來定義的。我們可以簡單的理解爲,Specification構造的就是查詢條件。

Specification接口中只定義瞭如下一個方法:

   //構造查詢條件
    /**
    *   root    :Root接口,代表查詢的根對象,可以通過root獲取實體中的屬性
    *   query   :代表一個頂層查詢對象,用來自定義查詢
    *   cb      :用來構建查詢,此對象裏有很多條件方法
    **/
    public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb);

 

5.1    使用Specifications完成條件查詢

 //依賴注入customerDao
    @Autowired
    private CustomerDao customerDao; 
    @Test
    public void testSpecifications() {
         //使用匿名內部類的方式,創建一個Specification的實現類,並實現toPredicate方法
        Specification <Customer> spec = new Specification<Customer>() {
           public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
               //cb:構建查詢,添加查詢方式   like:模糊匹配
               //root:從實體Customer對象中按照custName屬性進行查詢
               return cb.like(root.get("custName").as(String.class), "北京%");
           }
        };
        Customer customer = customerDao.findOne(spec);
        System.out.println(customer);
    }

5.2    基於Specifications的分頁查詢

    @Test
    public void testPage() {
        //構造查詢條件
        Specification<Customer> spec = new Specification<Customer>() {
           public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
               return cb.like(root.get("custName").as(String.class), "學校%");
           }
        };
       
        /**
         * 構造分頁參數
         *      Pageable : 接口
         *          PageRequest實現了Pageable接口,調用構造方法的形式構造
         *              第一個參數:頁碼(從0開始)
         *              第二個參數:每頁查詢條數
         */
        Pageable pageable = new PageRequest(0, 5);
       
        /**
         * 分頁查詢,封裝爲Spring Data Jpa 內部的page bean
         *      此重載的findAll方法爲分頁方法需要兩個參數
         *          第一個參數:查詢條件Specification
         *          第二個參數:分頁參數
         */
        Page<Customer> page = customerDao.findAll(spec,pageable);
       
    }

 

對於Spring Data JPA中的分頁查詢,是其內部自動實現的封裝過程,返回的是一個Spring Data JPA提供的pageBean對象。其中的方法說明如下:

 //獲取總頁數
int getTotalPages();
 //獲取總記錄數  
long getTotalElements();
//獲取列表數據
List<T> getContent();

 

5.3    方法對應關係

方法名稱

Sql對應關係

equle

filed = value

gt(greaterThan )

filed > value

lt(lessThan )

filed < value

ge(greaterThanOrEqualTo )

filed >= value

le( lessThanOrEqualTo)

filed <= value

notEqule

filed != value

like

filed like value

notLike

filed not like value

六 多表之間的關係和操作多表的操作步驟

表關係
		一對一
		一對多:
			一的一方:主表
			多的一方:從表
			外鍵:需要再從表上新建一列作爲外鍵,他的取值來源於主表的主鍵
		多對多:
			中間表:中間表中最少應該由兩個字段組成,這兩個字段做爲外鍵指向兩張表的主鍵,又組成了聯合主鍵

	講師對學員:一對多關係
			
	實體類中的關係
		包含關係:可以通過實體類中的包含關係描述表關係
		繼承關係
	
	分析步驟
		1.明確表關係
		2.確定表關係(描述 外鍵|中間表)
		3.編寫實體類,再實體類中描述表關係(包含關係)
		4.配置映射關係

6.1 數據庫中多表存在着三種關係

數據庫中多表之間存在着三種關係,如圖所示。

從圖可以看出,系統設計的三種實體關係分別爲:多對多、一對多和一對一關係。在實際開發中很少用到一對一關係,大多涉及到多表操作

6.2 表關係分析步驟

第一步:首先確定兩張表之間的關係。

        如果關係確定錯了,後面做的所有操作就都不可能正確。

第二步:在數據庫中實現兩張表的關係

第三步:在實體類中描述出兩個實體的關係

第四步:配置出實體類和數據庫表的關係映射(重點)

七 完成多表操作

7.1 一對多

7.1.1示例分析

客戶:指的一家公司

聯繫人:公司的員工

這樣客戶和聯繫人,即公司和員工的關係爲一對多。

7.1.2表關係建立

在一對多關係中,習慣把一的一方稱爲主表,多的一方稱爲從表。數據庫中建立一對多的關係,需要使用數據庫的外鍵約束。

7.1.3實體類關係建立以及映射配置

在實體類中,由於客戶是少的一方,它應該包含多個聯繫人,所以實體類要體現出客戶中有多個聯繫人的信息,代碼如下:

/**
 * 客戶的實體類
 * 明確使用的註解都是JPA規範的
 * 所以導包都要導入javax.persistence包下的
 */
@Entity//表示當前類是一個實體類
@Table(name="cst_customer")//建立當前實體類和表之間的對應關係
public class Customer implements Serializable {
	
	@Id//表明當前私有屬性是主鍵
	@GeneratedValue(strategy=GenerationType.IDENTITY)//指定主鍵的生成策略
	@Column(name="cust_id")//指定和數據庫表中的cust_id列對應
	private Long custId;
	@Column(name="cust_name")//指定和數據庫表中的cust_name列對應
	private String custName;
	@Column(name="cust_source")//指定和數據庫表中的cust_source列對應
	private String custSource;
	@Column(name="cust_industry")//指定和數據庫表中的cust_industry列對應
	private String custIndustry;
	@Column(name="cust_level")//指定和數據庫表中的cust_level列對應
	private String custLevel;
	@Column(name="cust_address")//指定和數據庫表中的cust_address列對應
	private String custAddress;
	@Column(name="cust_phone")//指定和數據庫表中的cust_phone列對應
	private String custPhone;
	
    //配置客戶和聯繫人的一對多關係
  	@OneToMany(targetEntity=LinkMan.class)
	@JoinColumn(name="lkm_cust_id",referencedColumnName="cust_id")
	private Set<LinkMan> linkmans = new HashSet<LinkMan>(0);
	
     // 省略get set toString方法
}

由於聯繫人是多的一方,在實體類中要體現出,每個聯繫人只能對應一個客戶,代碼如下:

/**
 * 聯繫人的實體類(數據模型)
 */
@Entity
@Table(name="cst_linkman")
public class LinkMan implements Serializable {
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	@Column(name="lkm_id")
	private Long lkmId;
	@Column(name="lkm_name")
	private String lkmName;
	@Column(name="lkm_gender")
	private String lkmGender;
	@Column(name="lkm_phone")
	private String lkmPhone;
	@Column(name="lkm_mobile")
	private String lkmMobile;
	@Column(name="lkm_email")
	private String lkmEmail;
	@Column(name="lkm_position")
	private String lkmPosition;
	@Column(name="lkm_memo")
	private String lkmMemo;

	//多對一關係映射:多個聯繫人對應客戶
	@ManyToOne(targetEntity=Customer.class)
	@JoinColumn(name="lkm_cust_id",referencedColumnName="cust_id")
	private Customer customer;//用它的主鍵,對應聯繫人表中的外鍵
    // 省略set get toString 方法

 

7.1.4映射的註解說明

@OneToMany:

     作用:建立一對多的關係映射

    屬性:

    targetEntityClass:指定多的多方的類的字節碼

    mappedBy:指定從表實體類中引用主表對象的名稱。

    cascade:指定要使用的級聯操作

    fetch:指定是否採用延遲加載

    orphanRemoval:是否使用孤兒刪除

 

@ManyToOne

    作用:建立多對一的關係

    屬性:

    targetEntityClass:指定一的一方實體類字節碼

    cascade:指定要使用的級聯操作

    fetch:指定是否採用延遲加載

    optional:關聯是否可選。如果設置爲false,則必須始終存在非空關係。

 

@JoinColumn

     作用:用於定義主鍵字段和外鍵字段的對應關係。

     屬性:

    name:指定外鍵字段的名稱

    referencedColumnName:指定引用主表的主鍵字段名稱

    unique:是否唯一。默認值不唯一

    nullable:是否允許爲空。默認值允許。

    insertable:是否允許插入。默認值允許。

    updatable:是否允許更新。默認值允許。

    columnDefinition:列的定義信息。

 

7.1.5一對多的操作

添加

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class OneToManyTest {
 
    @Autowired
    private CustomerDao customerDao;
   
    @Autowired
    private LinkManDao linkManDao;
   
   
    /**
     * 保存操作
     * 需求:
     * 保存一個客戶和一個聯繫人
     * 要求:
     * 創建一個客戶對象和一個聯繫人對象
     *  建立客戶和聯繫人之間關聯關係(雙向一對多的關聯關係)
     *  先保存客戶,再保存聯繫人
     * 問題:
     *      當我們建立了雙向的關聯關係之後,先保存主表,再保存從表時:
     *      會產生2條insert和1條update.
     *      而實際開發中我們只需要2條insert。
     * 
     */
    @Test
    @Transactional  //開啓事務
    @Rollback(false)//設置爲不回滾
    public void testAdd() {
        Customer c = new Customer();
        c.setCustName("大佬雲集中心");
        c.setCustLevel("VIP客戶");
        c.setCustSource("網絡");
        c.setCustIndustry("商業辦公");
        c.setCustAddress("北京市海淀區");
        c.setCustPhone("010-84389340");
       
        LinkMan l = new LinkMan();
        l.setLkmName("TBD聯繫人");
        l.setLkmGender("male");
        l.setLkmMobile("13811111111");
        l.setLkmPhone("010-34785348");
        l.setLkmEmail("[email protected]");
        l.setLkmPosition("老師");
        l.setLkmMemo("還行吧");
 
        c.getLinkMans().add(l);
        l.setCustomer(c);
        customerDao.save(c);
        linkManDao.save(l);
    }
}

但是這樣的保存,通過sql語句可以看出來,同樣的update語句發送了兩條,那麼配置放棄一方的維護全。

/**
     *放棄外鍵維護權的配置將如下配置改爲
     */
    //@OneToMany(targetEntity=LinkMan.class)
//@JoinColumn(name="lkm_cust_id",referencedColumnName="cust_id")   
//設置爲
    @OneToMany(mappedBy="customer")

刪除

   @Autowired
    private CustomerDao customerDao;
   
    @Test
    @Transactional
    @Rollback(false)//設置爲不回滾
    public void testDelete() {
        customerDao.delete(1l);
    }

刪除操作的說明如下:

刪除從表數據:可以隨時任意刪除。

刪除主表數據:

 ※ 有從表數據

  1、在默認情況下,它會把外鍵字段置爲null,然後刪除主表數據。如果在數據庫的表結構上,外鍵字段有非空約束,默認情況就會報錯了。

  2、如果配置了放棄維護關聯關係的權利,則不能刪除(與外鍵字段是否允許爲null,沒有關係)因爲在刪除時,它根本不會去更新從表的外鍵字段了。

  3、如果還想刪除,使用級聯刪除引用

※沒有從表數據引用:隨便刪

在實際開發中,級聯刪除請慎用!(在一對多的情況下)

 

級聯操作

級聯操作:指操作一個對象同時操作它的關聯對象

使用方法:只需要在操作主體的註解上配置cascade

    /**
     * cascade:配置級聯操作
     *      CascadeType.MERGE  級聯更新
     *      CascadeType.PERSIST 級聯保存:
     *      CascadeType.REFRESH 級聯刷新:
     *      CascadeType.REMOVE 級聯刪除:
     *      CascadeType.ALL    包含所有
     */
    @OneToMany(mappedBy="customer",cascade=CascadeType.ALL)

 

7.2 多對多

7.2.1示例分析

用戶:指的是咱們班的每一個同學。

角色:指的是咱們班同學的身份信息。

比如A同學,它是我的學生,其中有個身份就是學生,還是家裏的孩子,那麼他還有個身份是子女。

同時B同學,它也具有學生和子女的身份。

那麼任何一個同學都可能具有多個身份。同時學生這個身份可以被多個同學所具有。

所以說,用戶和角色之間的關係是多對多。

 

7.2.2表關係建立

 

7.2.3實體類關係建立以及映射配置

一個用戶可以具有多個角色,所以在用戶實體類中應該包含多個角色的信息,代碼如下:

/**
 * 用戶的數據模型
 */
@Entity
@Table(name="sys_user")
public class SysUser implements Serializable {
   
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="user_id")
    private Long userId;
    @Column(name="user_code")
    private String userCode;
    @Column(name="user_name")
    private String userName;
    @Column(name="user_password")
    private String userPassword;
    @Column(name="user_state")
    private String userState;
   
    //多對多關係映射
    @ManyToMany(mappedBy="users")
    private Set<SysRole> roles = new HashSet<SysRole>(0);

一個角色可以賦予多個用戶,所以在角色實體類中應該包含多個用戶的信息,代碼如下:

/**
 * 角色的數據模型
 */
@Entity
@Table(name="sys_role")
public class SysRole implements Serializable {
   
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="role_id")
    private Long roleId;
    @Column(name="role_name")
    private String roleName;
    @Column(name="role_memo")
    private String roleMemo;
   
    //多對多關係映射
    @ManyToMany
    @JoinTable(name="user_role_rel",//中間表的名稱
             //中間表user_role_rel字段關聯sys_role表的主鍵字段role_id
             joinColumns={@JoinColumn(name="role_id",referencedColumnName="role_id")},
             //中間表user_role_rel的字段關聯sys_user表的主鍵user_id
             inverseJoinColumns={@JoinColumn(name="user_id",referencedColumnName="user_id")}
    )
    private Set<SysUser> users = new HashSet<SysUser>(0);

7.2.4映射的註解說明

@ManyToMany

        作用:用於映射多對多關係

        屬性:

                 cascade:配置級聯操作。

                 fetch:配置是否採用延遲加載。

    targetEntity:配置目標的實體類。映射多對多的時候不用寫。

 

@JoinTable

    作用:針對中間表的配置

    屬性:

    nam:配置中間表的名稱

    joinColumns:中間表的外鍵字段關聯當前實體類所對應表的主鍵字段                                               

    inverseJoinColumn:中間表的外鍵字段關聯對方表的主鍵字段

   

@JoinColumn

    作用:用於定義主鍵字段和外鍵字段的對應關係。

    屬性:

    name:指定外鍵字段的名稱

    referencedColumnName:指定引用主表的主鍵字段名稱

    unique:是否唯一。默認值不唯一

    nullable:是否允許爲空。默認值允許。

    insertable:是否允許插入。默認值允許。

    updatable:是否允許更新。默認值允許。

    columnDefinition:列的定義信息。

 

7.2.5多對多的操作

保存

 @Autowired
    private UserDao userDao;
   
    @Autowired
    private RoleDao roleDao;
    /**
     * 需求:
     * 保存用戶和角色
     * 要求:
     * 創建2個用戶和3個角色
     * 讓1號用戶具有1號和2號角色(雙向的)
     * 讓2號用戶具有2號和3號角色(雙向的)
     *  保存用戶和角色
     * 問題:
     *  在保存時,會出現主鍵重複的錯誤,因爲都是要往中間表中保存數據造成的。
     * 解決辦法:
     * 讓任意一方放棄維護關聯關係的權利
     */
    @Test
    @Transactional  //開啓事務
    @Rollback(false)//設置爲不回滾
    public void test1(){
        //創建對象
        SysUser u1 = new SysUser();
        u1.setUserName("用戶1");
        SysRole r1 = new SysRole();
        r1.setRoleName("角色1");
        //建立關聯關係
        u1.getRoles().add(r1);
        r1.getUsers().add(u1);
        //保存
        roleDao.save(r1);
        userDao.save(u1);
    }

在多對多(保存)中,如果雙向都設置關係,意味着雙方都維護中間表,都會往中間表插入數據,中間表的2個字段又作爲聯合主鍵,所以報錯,主鍵重複,解決保存失敗的問題:只需要在任意一方放棄對中間表的維護權即可,推薦在被動的一方放棄,配置如下:

   //放棄對中間表的維護權,解決保存中主鍵衝突的問題
    @ManyToMany(mappedBy="roles")
    private Set<SysUser> users = new HashSet<SysUser>(0);

刪除

@Autowired
private UserDao userDao;
/**
 * 刪除操作
 * 在多對多的刪除時,雙向級聯刪除根本不能配置
 * 禁用
 *  如果配了的話,如果數據之間有相互引用關係,可能會清空所有數據
 */
@Test
@Transactional
@Rollback(false)//設置爲不回滾
public void testDelete() {
    userDao.delete(1l);
}

八 導航查詢

對象圖導航檢索方式是根據已經加載的對象,導航到他的關聯對象。它利用類與類之間的關係來檢索對象。例如:我們通過ID查詢方式查出一個客戶,可以調用Customer類中的getLinkMans()方法來獲取該客戶的所有聯繫人。對象導航查詢的使用要求是:兩個對象之間必須存在關聯關係。

 

查詢一個客戶,獲取該客戶下的所有聯繫人

@Autowired
    private CustomerDao customerDao;
   
    @Test
    //由於是在java代碼中測試,爲了解決no session問題,將操作配置到同一個事務中
    @Transactional
    public void testFind() {
        Customer customer = customerDao.findOne(5l);
        Set<LinkMan> linkMans = customer.getLinkMans();//對象導航查詢
        for(LinkMan linkMan : linkMans) {
            System.out.println(linkMan);
        }
    }

查詢一個聯繫人,獲取該聯繫人的所有客戶

@Autowired
    private LinkManDao linkManDao;
   
   
    @Test
    public void testFind() {
        LinkMan linkMan = linkManDao.findOne(4l);
        Customer customer = linkMan.getCustomer(); //對象導航查詢
        System.out.println(customer);
    }

對象導航查詢的問題分析

 

問題1:我們查詢客戶時,要不要把聯繫人查詢出來?

分析:如果我們不查的話,在用的時候還要自己寫代碼,調用方法去查詢。如果我們查出來的,不使用時又會白白的浪費了服務器內存。

解決:採用延遲加載的思想。通過配置的方式來設定當我們在需要使用時,發起真正的查詢。

配置方式:

    /**
     * 在客戶對象的@OneToMany註解中添加fetch屬性
     *      FetchType.EAGER :立即加載
     *      FetchType.LAZY :延遲加載
     */
    @OneToMany(mappedBy="customer",fetch=FetchType.EAGER)
    private Set<LinkMan> linkMans = new HashSet<>(0);

問題2:我們查詢聯繫人時,要不要把客戶查詢出來?

分析:例如:查詢聯繫人詳情時,肯定會看看該聯繫人的所屬客戶。如果我們不查的話,在用的時候還要自己寫代碼,調用方法去查詢。如果我們查出來的話,一個對象不會消耗太多的內存。而且多數情況下我們都是要使用的。

解決: 採用立即加載的思想。通過配置的方式來設定,只要查詢從表實體,就把主表實體對象同時查出來

配置方式

    /**
     * 在聯繫人對象的@ManyToOne註解中添加fetch屬性
     *      FetchType.EAGER :立即加載
     *      FetchType.LAZY :延遲加載
     */
   @ManyToOne(targetEntity=Customer.class,fetch=FetchType.EAGER)
   @JoinColumn(name="cst_lkm_id",referencedColumnName="cust_id")
    private Customer customer;

使用Specification查詢

/**
     * Specification的多表查詢
     */
    @Test
    public void testFind() {
        Specification<LinkMan> spec = new Specification<LinkMan>() {
           public Predicate toPredicate(Root<LinkMan> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
               //Join代表鏈接查詢,通過root對象獲取
               //創建的過程中,第一個參數爲關聯對象的屬性名稱,第二個參數爲連接查詢的方式(left,inner,right)
               //JoinType.LEFT : 左外連接,JoinType.INNER:內連接,JoinType.RIGHT:右外連接
               Join<LinkMan, Customer> join = root.join("customer",JoinType.INNER);
               return cb.like(join.get("custName").as(String.class),"傳智播客1");
           }
        };
        List<LinkMan> list = linkManDao.findAll(spec);
        for (LinkMan linkMan : list) {
           System.out.println(linkMan);
        }
    }

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章