03.SpringDataJPA

SpringDataJPA

Spring Data JPA 讓我們解脫了DAO層的操作服协,基本上所有CRUD都可以依賴于它來(lái)實(shí)現(xiàn),在實(shí)際的工作工程中公你,推薦使用Spring Data JPA + ORM(如:hibernate)完成操作,這樣在切換不同的ORM框架時(shí)提供了極大的方便膀值,同時(shí)也使數(shù)據(jù)庫(kù)層操作更加簡(jiǎn)單钠右,方便解耦

一答毫、工程搭建

1). maven坐標(biāo)

<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單元測(cè)試 -->
    <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>

    <!-- spring 對(duì)orm 的支持 -->
    <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>

    <!-- spring 對(duì) jpa 的支持 -->
    <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>${spring.version}</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>


<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.7.0</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
</build>

2). spring容器整合SpringDataJPA配置

根據(jù)項(xiàng)目需求修改

<?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 配置數(shù)據(jù)庫(kù)連接池; -->
    <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="abc123" />
    </bean>

    <!-- 2.配置entityManagerFactory 工廠 -->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />

        <!-- 【配置實(shí)體類的包掃描路徑仪搔!每個(gè)實(shí)體類對(duì)應(yīng)一張表屠升,靠注解綁定關(guān)系】 -->
        <property name="packagesToScan" value="com.lingting.entity" />

        <property name="persistenceProvider">
            <!-- 持久化方案提供商嫩码,這里選擇Hibernate -->
            <bean class="org.hibernate.jpa.HibernatePersistenceProvider" />
        </property>
        <!--JPA的供應(yīng)商適配器誉尖,Spring提供的!-->
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <!-- 關(guān)閉自動(dòng)生成表的功能【雞肋铸题!】 -->
                <property name="generateDdl" value="false" />
                <!-- 枚舉類型的數(shù)據(jù)庫(kù)類型 -->
                <property name="database" value="MYSQL" />
                <!-- 數(shù)據(jù)庫(kù)“方言”配置 -->
                <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
                <!-- 控制臺(tái)顯示執(zhí)行的sql語(yǔ)句 -->
                <property name="showSql" value="true" />
            </bean>
        </property>

        <!-- jpa “方言”:不同提供商實(shí)現(xiàn)的高級(jí)特性释牺,可選 -->
        <property name="jpaDialect">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
        </property>

        <!-- 【方便演示,實(shí)際中不要配置】雞肋配置回挽!注入jpa的配置信息
        加載jpa的基本信息和jpa實(shí)現(xiàn)方式(hibernate)的配置信息
        hibernate.hbm2ddl.auto:是否自動(dòng)創(chuàng)建數(shù)據(jù)庫(kù)表

        <property name="jpaProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">none</prop>
            </props>
        </property>
        -->
    </bean>

    <!-- 整合spring data jpa没咙;動(dòng)態(tài)代理、切面掃描的包路徑千劈,dao層的接口寫在此中-->
    <jpa:repositories base-package="com.lingting.dao"
                      transaction-manager-ref="transactionManager"
                      entity-manager-factory-ref="entityManagerFactory"/>

    <!-- 3.事務(wù)管理器-->
    <!-- JPA事務(wù)管理器: 底層估計(jì)使用的本地線程  -->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <!-- 聲明式事務(wù)控制 -->

    <!-- 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 切面表達(dá)式-->
    <aop:config>
        <aop:pointcut id="pointcut" expression="execution(* com.lingting.service.*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" />
    </aop:config>

    <!-- 其他注解掃描配置 spring 相關(guān) -->
    <context:component-scan base-package="com.lingting"/>
</beans>

二祭刚、實(shí)體類與表之間的映射關(guān)系配置

以下配置省略get/set/toString方法,

1). 一對(duì)多的關(guān)系

  1. Customer表墙牌,主表涡驮, 一的關(guān)系

在從表中維護(hù)外鍵信息,主表中參照從表對(duì)應(yīng)的屬性即可喜滨!

import javax.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

@Entity // 實(shí)體類
@Table(name = "cst_customer") // 對(duì)應(yīng)的表關(guān)系
public class Customer implements Serializable {

    @Id // 主鍵
    @GeneratedValue(strategy = GenerationType.IDENTITY) // 主鍵生成策略
    @Column(name = "cust_id") // 主鍵字段名
    private Long custId; // 客戶主鍵 屬性對(duì)應(yīng)主鍵字段

    @Column(name = "cust_name")
    private String custName;//客戶名稱

    /** 配置客戶和聯(lián)系人之間的關(guān)系:客戶 一對(duì)多 聯(lián)系人
     【實(shí)際生產(chǎn)中建議不要使用外鍵捉捅,使用外鍵的分布式方案下的數(shù)據(jù)庫(kù)集群性能是非常糟糕的!】
     @OneToMany 配置一對(duì)多關(guān)系虽风,參數(shù)為有關(guān)系的實(shí)體類的字節(jié)碼對(duì)象
     一般主表上【放棄對(duì)外鍵的維護(hù)】棒口,外鍵的維護(hù)交給從表即可

     mappedBy 表示參照從表中的 customer 屬性來(lái)配置,也就是說(shuō)從表中必須有 customer屬性辜膝!
     cascade 級(jí)聯(lián)操作无牵,主表的增刪改同時(shí)影響從表記錄的增刪改!枚舉值如下
          CascadeType.ALL    : 所有
          CascadeType.MERGE  : 更新
          CascadeType.PERSIST: 保存
          CascadeType.REMOVE : 刪除
     fetch: 配置關(guān)聯(lián)對(duì)象的加載方式
           EAGER : 立即加載【從多的一方查一的一方為默認(rèn)】
           LAZY  : 懶加載【從一的一方查多的一方為默認(rèn)】
     */
    @OneToMany(mappedBy = "customer", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private Set<LinkMan> linkMans = new HashSet<>();

    /** 其他字段和get/set/toString略 */
  1. LinkMan表厂抖,從表茎毁, 多的關(guān)系

不需要額外設(shè)置外鍵屬性字段!忱辅,在配置相互關(guān)系中使用注解配置即可七蜘!

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

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

    /** 配置聯(lián)系人到客戶的多對(duì)一關(guān)系
     @ManyToOne 配置多對(duì)一
     @JoinColumn 【配置外鍵信息】谭溉,指向主表的主鍵
     */
    @ManyToOne(targetEntity = Customer.class)
    @JoinColumn(name = "lkm_cust_id", referencedColumnName = "cust_id")
    private Customer customer;

    /** 其他字段和get/set/toString略,其他字段不需要外鍵屬性 */

2). 多對(duì)多的關(guān)系

用戶選擇角色橡卤,所以邏輯上主動(dòng)權(quán)在User實(shí)體類上

  1. User表夜只,主動(dòng)的一方

擁有維護(hù)主鍵的權(quán)限,不要同時(shí)將被動(dòng)的一方有維護(hù)權(quán)限蒜魄,容易出錯(cuò)扔亥!

import javax.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

@Entity
@Table(name = "sys_user")
public class User implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "user_id")
    private Long userId;

    @Column(name = "user_name")
    private String userName;

    @Column(name = "user_age")
    private Integer age;

    /** 多對(duì)多的關(guān)系
        被動(dòng)的一方放棄維護(hù)外鍵的權(quán)限,也就是Role實(shí)體類中放棄
     fetch: 配置關(guān)聯(lián)對(duì)象的加載方式
         EAGER : 立即加載
         LAZY  : 懶加載【默認(rèn)】
     */
    @ManyToMany(targetEntity = Role.class,cascade = CascadeType.ALL, fetch = FetchType.LAZY) // 多對(duì)多關(guān)系谈为,需要對(duì)方實(shí)體類字節(jié)碼
    @JoinTable(name = "sys_user_role",  // 中間表名稱
            // joinColumns: 當(dāng)前對(duì)象在中間表的外鍵旅挤,以及外鍵指向的當(dāng)前對(duì)象的主鍵
            joinColumns = {@JoinColumn(name = "sys_user_id", referencedColumnName = "user_id")},
            // 對(duì)方對(duì)象在中間表的外鍵,以及外鍵指向的對(duì)方對(duì)象的主鍵
            inverseJoinColumns = {@JoinColumn(name = "sys_role_id", referencedColumnName = "role_id")}
    )
    private Set<Role> roles = new HashSet<>();

    /** 其他字段和get/set/toString略 */
  1. Role表伞鲫,被動(dòng)的一方
import javax.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

@Entity
@Table(name = "sys_role")
public class Role implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "role_id")
    private Long roleId;

    @Column(name = "role_name")
    private String roleName;

    /**
     配置多對(duì)多粘茄,但是放棄外鍵維護(hù)的權(quán)限
     */
    @ManyToMany(mappedBy = "roles")
    private Set<User> users = new HashSet<>();
    /** 其他字段和get/set/toString略 */

三、動(dòng)態(tài)代理dao層接口配置

1). CustomerDao

import com.lingting.entity.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

/** 集成了如下接口的接口就符合 SpringDataJPA 規(guī)范【只是spring設(shè)計(jì)的規(guī)范】
 * JpaRepository<T, ID>         簡(jiǎn)單查詢
 * JpaSpecificationExecutor<T>  高級(jí)查詢
 *     T 泛型為 pojo實(shí)體類
 *     ID 為pojo中主鍵字段的數(shù)據(jù)類型
 *  底層估計(jì)是用【動(dòng)態(tài)代理】實(shí)現(xiàn)的動(dòng)態(tài)代理類秕脓!
 */
public interface CustomerDao extends JpaRepository<Customer, Long>, JpaSpecificationExecutor<Customer> {

     /** 后面介紹的一些與Customer實(shí)體類相關(guān)的接口抽象方法寫在此柒瓣! */
}

2). 其他dao

...

public interface LinkManDao extends JpaRepository<LinkMan, Long>, JpaSpecificationExecutor<LinkMan> { }

public interface RoleDao extends JpaRepository<Role, Long>, JpaSpecificationExecutor<Role> { }

public interface UserDao extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> { }

四、單表操作

測(cè)試類模板

import com.lingting.entity.Customer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.persistence.criteria.*;
import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class JpaSpecificationExecutorTest {
    @Autowired
    private CustomerDao customerDao;

    @Autowired
    private LinkManDao linkManDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    /** 下方的測(cè)試方法寫在此 */
}

1). 使用JpaRepository接口中提供的原生抽象方法

/** ~~~~~~~~~~~~~~~~~ JpaRepository接口中的原生方法 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/**
 * 立即查詢:根據(jù)id進(jìn)行查詢
 * 立即加載 em.find()
 */
@Test
public void findOne() {
    Customer one = customerDao.findOne(5L);
    System.out.println(one);
}

/**
 * 根據(jù)id查詢
 * 懶加載:由于設(shè)計(jì)上的原因吠架,需要加上 事務(wù)注解芙贫,否則會(huì)報(bào)錯(cuò)
 *  em.getReference()
 */
@Test
@Transactional
public void getOne() {
    Customer one = customerDao.getOne(4L);
    System.out.println(one);
}

/**
 * 查詢所有; jdk8+
 */
@Test
public void findAll() {
    List<Customer> all = customerDao.findAll();
    all.forEach(System.out::println);
}

/**
 * save:
 *     新增:id為null
 *     跟新:id不為null
 *          跟新的步驟:必須先查詢,然后跟新傍药!否則null會(huì)覆蓋原有值磺平!
 */
@Test
public void save() {
    Customer c = new Customer();
    c.setCustName("紅岸工程");
    c.setCustIndustry("外星生命探索");
    customerDao.save(c);

    // 根據(jù)id 查詢,然后跟新
    Customer one = customerDao.findOne(6L);
    one.setCustIndustry("外星生命探索");
    customerDao.save(one);
}

/**
 * 刪除
 */
@Test
public void delete() {
    customerDao.delete(6L);
}

/**
 * 聚合查詢
 */
@Test
public void aggregation() {
    long count = customerDao.count();
    System.out.println(count);
}

/**
 * 根據(jù)id判斷對(duì)象是否存在
 */
@Test
public void exists() {
    boolean exists = customerDao.exists(3L);
    System.out.println(exists);
}

2). 使用jpql方式拐辽,在接口中添加自定義抽象方法

  1. CustomerDao接口中的抽象方法
/** ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 * jpql 根據(jù)客戶名進(jìn)行查詢
 * ?占位符后面的索引代表簽名的索引拣挪,從1開始!
 */
@Query(value = "from Customer where custName = ?1 and custIndustry = ?2")
public List<Customer> findByCustName(String custName, String custIndustry);

/**
 * 根據(jù)id跟新客戶名
 * @Query: 這里用于存放 jpql語(yǔ)句【設(shè)計(jì)的真不行俱诸,一個(gè)跟新語(yǔ)句為何要用Query注解菠劝?】
 * @Modifying: 指定為跟新操作
 */
@Query("update Customer set custName = ?2 where custId = ?1")
@Modifying
public void updateCustomer(long custId, String custName);
  1. 測(cè)試類中的方法
/** ~~~~~~~~~~~~~~~~~ jpql,在接口中添加抽象方法 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

@Test
public void findByCustName() {
    List<Customer> list = customerDao.findByCustName("紅岸工程", "外星生命探索");
    list.forEach(System.out::println);
}

/** jpql 的跟新/刪除操作
 * @Transactional: 需要手動(dòng)添加事務(wù)
 * @Rollback(value=false): Junit默認(rèn)回滾事務(wù)睁搭,需要修改【Junit中需要赶诊,service層中是不需要的!】
 */
@Test
@Transactional
@Rollback(value = false)
public void updateCustomer() {
    customerDao.updateCustomer(4L, "星環(huán)城");
}

3). 使用徹底的方法名稱進(jìn)行查詢

jpql更加深入的封裝,直接解析方法名介袜,需要在dao中進(jìn)行定義甫何,以便動(dòng)態(tài)代理進(jìn)行增強(qiáng)

  1. CustomerDao接口中的抽象方法

/** ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 * 方法名稱規(guī)則查詢【沒(méi)得注解出吹,對(duì)jpql更加深入的封裝】
 * 注意參數(shù)的個(gè)數(shù)和位置要對(duì)應(yīng)遇伞!
 * 只需要定義SpringDataJPA方法命名的規(guī)則進(jìn)行命名方法名,就可以進(jìn)行指定查詢捶牢!
 * 如下幾種方式:【可組合: findBy+屬性名+查詢方式+And+屬性名...】
 *      findByAttribute
 *      findByAttr1AndAttr2...
 *      findByAttributeLike
 *      findByAttributeIsNull
 *      findByLastnameOrFirstname
 *      ...
 */
public List<Customer> findByCustNameAndCustIndustry(String custName, String custIndustry);

public List<Customer> findByCustNameLike(String custName);

public List<Customer> findByCustNameStartingWith(String custName);
  1. 測(cè)試類中的方法
/** ~~~~~~~~~~~~~~~~~ 方法名稱規(guī)范查詢 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

@Test
public void findByCustNameAndCustIndustry() {
    List<Customer> list = customerDao.findByCustNameAndCustIndustry("紅岸工程", "外星生命探索");
    list.forEach(System.out::println);
}

@Test
public void findByCustNameLike() {
    List<Customer> byCustNameLike = customerDao.findByCustNameLike("星%");
    byCustNameLike.forEach(System.out::println);
}

@Test
public void findByCustNameStartingWith() {
    List<Customer> list = customerDao.findByCustNameStartingWith("新");
    list.forEach(System.out::println);
}
  1. 方法名稱轉(zhuǎn)換對(duì)應(yīng)關(guān)系
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)

4). 使用JpaSpecificationExecutor接口中提供的原生抽象方法

組合查詢鸠珠、排序巍耗、分頁(yè)綜合查詢?nèi)缦?/p>

/**
 * 自定義查詢條件
 * 實(shí)現(xiàn) Specification接口,提供查詢對(duì)象的泛型
 * 實(shí)現(xiàn)toPredicate方法渐排,構(gòu)造查詢條件
 * 使用方法中的兩個(gè)參數(shù)即可【還有一個(gè)為頂層查詢條件炬太,幾乎不會(huì)使用】
 *      Root: 獲取需要查詢的對(duì)象屬性
 *      CriteriaBuilder: 構(gòu)造查詢條件,內(nèi)部封裝了很多查詢條件(模糊匹配驯耻,精準(zhǔn)匹配)
 */
@Test
public void dynamicQuery() {
    Specification<Customer> spec = new Specification<Customer>() {
        @Override
        public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            // 案例:

            // 1.獲取被比較的屬性
            Path<Object> custName = root.get("custName");
            Path<Object> custIndustry = root.get("custIndustry");
            Path<Object> custLevel = root.get("custLevel");

            // 2.構(gòu)造查詢條件:參數(shù):被比較的對(duì)象亲族、比較的值

            // equal
            Predicate p1 = cb.equal(custName, "星環(huán)城");

            // 其他方式
            Predicate p2 = cb.like(custIndustry.as(String.class), "太空%");

            // gt 大于; ge 大于等于 lt/le
            Predicate p3 = cb.gt(custLevel.as(int.class), 1);

            // 邏輯組合關(guān)系,可變長(zhǎng)參數(shù)可缚!
            Predicate p4 = cb.or(p2, p3);
            Predicate p5 = cb.and(p1, p4);

            return p5;
        }
    };
    // 當(dāng)返回值之后一個(gè)時(shí)霎迫,可使用:
    // Customer c = customerDao.findOne(spec);

    List<Customer> list1 = customerDao.findAll(spec);

    // 排序,第一個(gè)參數(shù)為排序方式(枚舉)帘靡;第二個(gè)為需要排序的字段
    Sort sort = new Sort(Sort.Direction.DESC, "custId");
    List<Customer> list2 = customerDao.findAll(spec, sort);

    // 分頁(yè)查詢, 參數(shù)1:查詢的頁(yè)數(shù)知给,參數(shù)2:每頁(yè)的條數(shù)
    Pageable pageable = new PageRequest(2 - 1, 2);
    Page<Customer> page = customerDao.findAll(spec, pageable);
    List<Customer> content = page.getContent();
    long totalElements = page.getTotalElements();
    int totalPages = page.getTotalPages();

    content.forEach(System.out::println);
    System.out.println(totalElements);
    System.out.println(totalPages);

}

CriteriaBuilder對(duì)象方法對(duì)應(yīng)關(guān)系表

方法名稱 Sql對(duì)應(yīng)關(guān)系
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

5). 【了解】使用原生sql查詢,在dao中進(jìn)行定義

  1. dao
/** ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 * 使用原生sql查詢;【了解】
 * 將@Query注解的nativeQuery參數(shù)設(shè)置為true
 * 返回值很奇怪描姚,將每條記錄的字段放入一個(gè)Object[] 中涩赢!
 * 還得自己封裝成pojo,多麻煩轩勘!
 */
@Query(value = "select * from cst_customer where cust_name like ?1", nativeQuery = true)
public List<Object[]> findAllByNative(String custName);
  1. 測(cè)試
/** ~~~~~~~~~~~~~~~~~ 【了解】原生sql查詢 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

/**
 * 使用原生的sql語(yǔ)句進(jìn)行查詢【了解】
 */
@Test
public void findAllByNative() {
    List<Object[]> list = customerDao.findAllByNative("星%");
    for (Object[] objects : list) {
        System.out.println(Arrays.toString(objects));
    }
}

五筒扒、多表測(cè)試

多表主要是配置,見(jiàn)上面的實(shí)體類配置绊寻;

1). 級(jí)聯(lián)測(cè)試

注意:在實(shí)際開發(fā)中霎肯,級(jí)聯(lián)刪除請(qǐng)慎用!(在一對(duì)多的情況下)

/** 一對(duì)多
 * 保存一個(gè)客戶榛斯,一個(gè)聯(lián)系人
 */
@Test
@Transactional
@Rollback(value = false)
public void addOne() {
    Customer customer = new Customer();
    customer.setCustName("華為");

    LinkMan linkMan = new LinkMan();
    linkMan.setLkmName("柔絲");

    // 級(jí)聯(lián)操作,兩個(gè)關(guān)聯(lián)都需要設(shè)置
    customer.getLinkMans().add(linkMan);
    linkMan.setCustomer(customer);

    // 級(jí)聯(lián)操作后观游,只需要保存一個(gè)
    customerDao.save(customer);
}

/** 多對(duì)多
 */
@Test
@Transactional
@Rollback(false)
public void add() {
    // 新建實(shí)體類
    User user = new User();
    user.setUserName("小馬");

    Role role = new Role();
    role.setRoleName("CEO");

    // 綁定關(guān)系
    user.getRoles().add(role);
    role.getUsers().add(user);

    // 級(jí)聯(lián)操作,只操作主表
    userDao.save(user);
}

2). 對(duì)象導(dǎo)航測(cè)試

/** 一對(duì)多 對(duì)象導(dǎo)航查詢
 * 對(duì)象導(dǎo)航查詢:
 *  jpa的機(jī)制驮俗,通過(guò) 對(duì)象.get關(guān)聯(lián)的屬性() 即可進(jìn)行懶加載查詢其他表相關(guān)聯(lián)的數(shù)據(jù)
 *  注意:在junit中需要加上@Transactional事務(wù)注解解決 no session問(wèn)題
 */
@Test
@Transactional
public void objectNavigate() {
    Customer customer = customerDao.findOne(1L);

    // 下面的執(zhí)行過(guò)程為懶加載機(jī)制【獲取的是linkMans的一個(gè)動(dòng)態(tài)代理對(duì)象】【注意idea工具導(dǎo)致的假象】
    Set<LinkMan> linkMans = customer.getLinkMans();

    // 執(zhí)行下面時(shí)才開始查詢懂缕!
    linkMans.forEach(System.out::println);
}

3). 使用Specification查詢

/**
 * Specification的多表查詢
 */
@Test
public void testFind() {
    Specification<LinkMan> spec = new Specification<LinkMan>() {
        public Predicate toPredicate(Root<LinkMan> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            //Join代表鏈接查詢,通過(guò)root對(duì)象獲取
            //創(chuàng)建的過(guò)程中王凑,第一個(gè)參數(shù)為關(guān)聯(lián)對(duì)象的屬性名稱搪柑,第二個(gè)參數(shù)為連接查詢的方式(left,inner索烹,right)
            //JoinType.LEFT : 左外連接,JoinType.INNER:內(nèi)連接,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);
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末工碾,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子百姓,更是在濱河造成了極大的恐慌渊额,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,204評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異旬迹,居然都是意外死亡火惊,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,091評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門奔垦,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)屹耐,“玉大人,你說(shuō)我怎么就攤上這事椿猎』塘耄” “怎么了?”我有些...
    開封第一講書人閱讀 164,548評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵犯眠,是天一觀的道長(zhǎng)俗他。 經(jīng)常有香客問(wèn)我,道長(zhǎng)阔逼,這世上最難降的妖魔是什么兆衅? 我笑而不...
    開封第一講書人閱讀 58,657評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮嗜浮,結(jié)果婚禮上羡亩,老公的妹妹穿的比我還像新娘。我一直安慰自己危融,他們只是感情好畏铆,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,689評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著吉殃,像睡著了一般辞居。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上蛋勺,一...
    開封第一講書人閱讀 51,554評(píng)論 1 305
  • 那天瓦灶,我揣著相機(jī)與錄音,去河邊找鬼抱完。 笑死贼陶,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的巧娱。 我是一名探鬼主播碉怔,決...
    沈念sama閱讀 40,302評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼禁添!你這毒婦竟也來(lái)了撮胧?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,216評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤老翘,失蹤者是張志新(化名)和其女友劉穎芹啥,沒(méi)想到半個(gè)月后锻离,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,661評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡叁征,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,851評(píng)論 3 336
  • 正文 我和宋清朗相戀三年纳账,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了逛薇。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片捺疼。...
    茶點(diǎn)故事閱讀 39,977評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖永罚,靈堂內(nèi)的尸體忽然破棺而出啤呼,到底是詐尸還是另有隱情,我是刑警寧澤呢袱,帶...
    沈念sama閱讀 35,697評(píng)論 5 347
  • 正文 年R本政府宣布官扣,位于F島的核電站,受9級(jí)特大地震影響羞福,放射性物質(zhì)發(fā)生泄漏惕蹄。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,306評(píng)論 3 330
  • 文/蒙蒙 一治专、第九天 我趴在偏房一處隱蔽的房頂上張望卖陵。 院中可真熱鬧,春花似錦张峰、人聲如沸泪蔫。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,898評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)撩荣。三九已至,卻和暖如春饶深,著一層夾襖步出監(jiān)牢的瞬間餐曹,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,019評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工敌厘, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留凸主,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,138評(píng)論 3 370
  • 正文 我出身青樓额湘,卻偏偏與公主長(zhǎng)得像卿吐,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子锋华,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,927評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容

  • 這部分主要是開源Java EE框架方面的內(nèi)容嗡官,包括Hibernate、MyBatis毯焕、Spring衍腥、Spring ...
    雜貨鋪老板閱讀 1,385評(píng)論 0 2
  • 一. Java基礎(chǔ)部分.................................................
    wy_sure閱讀 3,811評(píng)論 0 11
  • 在一個(gè)方法內(nèi)部定義的變量都存儲(chǔ)在棧中磺樱,當(dāng)這個(gè)函數(shù)運(yùn)行結(jié)束后,其對(duì)應(yīng)的棧就會(huì)被回收婆咸,此時(shí)竹捉,在其方法體中定義的變量將不...
    Y了個(gè)J閱讀 4,418評(píng)論 1 14
  • 世界上最美的不是日出時(shí)的天空之城,也不是雨過(guò)天晴的絢爛彩虹尚骄,而是玩耍時(shí)孩童純真的笑臉块差。 這個(gè)暑假家里忙著裝修,看孩...
    北夢(mèng)沐曦閱讀 832評(píng)論 0 1
  • 你又開始躲藏倔丈,又開始游離憨闰,翻看你的手機(jī)是多么愚蠢的事,愚蠢在我認(rèn)輸了需五,我在乎你監(jiān)控你鹉动,我多想做個(gè)高傲的什么都...
    回歸的旅程閱讀 159評(píng)論 0 0