spring data jpa 教程

目录

spring Data jpa 的操作

导入依赖:

spring的配置文件:

编写实体类:

编写dao层接口:

编写测试类:

总结:

spring-data JPA的执行过程

复杂查询:

动态查询:JpaSpecificationExecutor方法列表


spring Data JPA 是在改进数据访问层的实现来提升开发效率。可以自动生成数据库和表。

它是spring提供的一套简化jpa开发的框架,按照约定好的规则进行(方法命名)去写dao 层接口, 就可以在不写接口的情况下实现对数据库的访问和操作。

同时也提供了很多除了CRUD之外的功能,如分页、排序、复杂查询的。

spring Data jpa 的操作

1.搭建环境,创建工程,配置spring文件,编写实体类

使用jpa注解配置映射关系

  1. 编写一个符合springdata jap的dao层接口

    导入依赖:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    ​
        <groupId>org.example</groupId>
        <artifactId>JPA</artifactId>
        <version>1.0-SNAPSHOT</version>
        <properties>
            <spring.version>5.0.2.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.12</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>
    <!--        ioc的相关坐标-->
            <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对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 -->
    <!--        mysql的驱动包-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql.version}</version>
            </dependency>
            <!-- spring data jpa 的坐标-->
            <dependency>
                <groupId>org.springframework.data</groupId>
                <artifactId>spring-data-jpa</artifactId>
                <version>1.9.0.RELEASE</version>
            </dependency>
    <!--        是spring提供的对junit的单元测试的坐标-->
            <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>
    </project>

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.xs
       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/study" />
        <property name="user" value="root" />
        <property name="password" value="lolbingcom199910" />
    </bean>
​
    <!-- 2.配置entityManagerFactory对象交给spring容器管理 -->
    <bean id="entityManagerFactory"
          class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
<!--        扫描实体类所在的包-->
        <property name="packagesToScan" value="com.xinzhi.domain" />
<!--        jpa的实现厂家-->
        <property name="persistenceProvider">
            <bean class="org.hibernate.jpa.HibernatePersistenceProvider" />
        </property>
        <!--JPA的供应商适配器-->
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<!--                代表配置是否自动创建数据库表 false不用 想用改为true-->
                <property name="generateDdl" value="false" />
<!--                指定数据库类型-->
                <property name="database" value="MYSQL" />
<!--                数据库方言:支持的特有语法-->
                <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
<!--                是否显示sql语句-->
                <property name="showSql" value="true" />
            </bean>
​
        </property>
<!--        jpa的方言:高级的特性  配置上了这个说明springdata jpa也有了HibernateJpaDialect的高级特性-->
        <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.xinzhi.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.xinzhi.service.*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" />
    </aop:config>
​
    <context:component-scan base-package="com.xinzhi"></context:component-scan>
​
    <!--组装其它 配置文件-->
</beans>

编写实体类:

package com.xinzhi.domain;
​
import javax.persistence.*;
​
/**
 * 1.实体类和表的映射关系
 * @Entity 声明实体类
 * @Table 配置实体类和表的映射关系
 * 2.类中属性和表中字段的映射关系
 * @Id 声明主键的配置
 * @GeneratedValue GenerationType.IDENTITY : 自增,mysql
 *                 底层数据库必须支持自动增长(底层数据库支持的自动增长方式,对id自增)
 *                 GenerationType.SEQUENCE : 序列,oracle
 *                 底层数据库必须支持序列
 *                 GenerationType.TABLE : jpa提供的一种机制,通过一张数据库表的形式帮助我们完成主键自增
 *                 GenerationType.AUTO : 由程序自动的帮助我们选择主键生成策略
 * @Column 配置属性和字段的映射关系
 */
@Entity
//name = 表示的是表的名称
@Table(name = "cst_customer")
public class Customer {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "cust_id")
    private Integer custId;
    @Column(name = "cust_address")
    private String custAddress;
    @Column(name = "cust_industry")
    private String custIndustry;
    @Column(name = "cust_leave")
    private String custLeave;
    @Column(name = "cust_phone")
    private String custPhone;
    @Column(name = "cust_source")
    private String custSource;
​
    public Integer getCustId() {
        return custId;
    }
​
    public void setCustId(Integer 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 getCustLeave() {
        return custLeave;
    }
​
    public void setCustLeave(String custLeave) {
        this.custLeave = custLeave;
    }
​
    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 + '\'' +
                ", custLeave='" + custLeave + '\'' +
                ", custPhone='" + custPhone + '\'' +
                ", custSource='" + custSource + '\'' +
                '}';
    }
}

编写dao层接口:

dao层接口的编写规范:1.需要继承两个接口(jpaRepository,jpaSpecificationExecutor)

2.需要提供影响的泛型

3.不需要编写实现类(这两个接口就是在做基本的增删改查,以及一些复杂的查询)

package com.xinzhi.dao;
​
​
import com.xinzhi.domain.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
​
/**
 * 符合springdatajpa的dao层接口规范
 * JpaRepository<操作的实体类类型,实体类中主键属性的类型>
 *  *          * 封装了基本CRUD操作
 *  *      JpaSpecificationExecutor<操作的实体类类型>
 *  *          * 封装了复杂查询(分页)
 */
public interface CustomerDao extends JpaRepository<Customer,Integer>, JpaSpecificationExecutor<Customer> {
}

现在就可以使用dao了,不用写实现类,现在就可以增删改查了

编写测试类:

package com.xinzhi.test;
​
import com.xinzhi.dao.CustomerDao;
import com.xinzhi.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)//声明spring提供的单元测试环境
@ContextConfiguration(locations = "classpath:applicationContext.xml")//指定spring容器的配置信息
public class CustomerDaoTest {
    @Autowired
    private CustomerDao customerDao;
  /**
     * 根据id从数据库查询
     *      @Transactional : 保证getOne正常运行(事务)
     *
     *  findOne:
     *      em.find()           :立即加载
     *  getOne:
     *      em.getReference     :延迟加载
     *      * 返回的是一个客户的动态代理对象
     *      * 什么时候用,什么时候查询
     */
@Test
    public  void  testFindOne(){
//    Customer one = customerDao.findOne(1);
    List<Customer> all = customerDao.findAll();
    System.out.println(all);
}
     @Test
    @Transactional
    public void  testGetOne() {
        Customer customer = customerDao.getOne(1);
        System.out.println(customer);
    }
​
    /**
     * 删除
     */
    @Test
    public void testDelete () {
        customerDao.delete(3);
    }
@Test
/**
 * save : 保存或者更新
 *      根据传递的对象是否存在主键id,
 *      如果没有id主键属性:保存
 *      存在id主键属性,根据id查询数据,更新数据
 */
    public void  textsave(){
        Customer customer = new Customer();
        customer.setCustaddress("das");
        customer.setCustindustry("IT");
        customer.setCustleave("VIP");
    customerDao.save(customer);
}

我在运行的时候发生了如下报错:

Warning:java: 源值1.5已过时, 将在未来所有发行版中删除 Warning:java: 目标值1.5已过时, 将在未来所有发行版中删除 Warning:java: 要隐藏有关已过时选项的警告, 请使用 -Xlint:-options。

原因:IDEA工具如果不配置,默认会将源代码JDK版本设置为1.5,目标代码JDK版本设置为1.5。

解决办法:


/**
 * 查询所有
 */
@Test
public void testFindAll() {
    List<Customer> list = customerDao.findAll();
    for(Customer customer : list) {
        System.out.println(customer);
    }
}

/**
 * 测试统计查询:查询客户的总数量
 *      count:统计总条数
 */
@Test
public void testCount() {
    long count = customerDao.count();//查询全部的客户数量
    System.out.println(count);
}

/**
 * 测试:判断id为4的客户是否存在
 *      1. 可以查询以下id为4的客户
 *          如果值为空,代表不存在,如果不为空,代表存在
 *      2. 判断数据库中id为4的客户的数量
 *          如果数量为0,代表不存在,如果大于0,代表存在
 */
@Test
public void  testExists() {
    boolean exists = customerDao.exists(4);
    System.out.println("id为4的客户 是否存在:"+exists);
 }
}

总结:

以上我们完成了基本的增删改查的方法

总结一下:findOne方法:根据id查询

sava:保存或更新 如果没有id主键属性:保存

有id主键属性:根据id查询数据,更新数据

delete(id):根据id删除

findAll():查询全部

count:查数据库的总条数

这里有个问题 接口不能干活,而我们jpa只有接口,那他是怎么干活的?

真正发挥作用的是接口的实现类,而我们的代码中没有实现类,那就说明在程序的执行过程中 自动的帮我们动态的生成了接口的实现类对象。

问题又来了,那是如何生成实现类对象的?

因为有 动态代理 可以帮我们生成基于接口的实现类对象

spring-data JPA的执行过程

1.通过JDKDynamicAopProxy的invoke方法创建一个动态代理对象

2.SimpleJpaRepository当中封装了jpa的操作,(借助jpa的api完成数据库的crud )

3.通过hibernate 完成数据库操作(hibernate 封装了jdbc)

复杂查询:

1.借助接口定义好的方法进行查询:findone(id)根据id查询

2.jpql的查询方式:

jpql:

jpq查询语言 特点:查询的是类和类中的属性(和sql类似)

如何实现?

*需要jpql语句配置到接口的方法上

a.特有的查询:在dao接口上配置方法

b.在新添加的方法上,使用注解配置jpql查询语句 @Query

下面我们来实现一下jpql查询:

首先在dao层编写:

/**
 * 根据客户名称查询客户
 * 使用jpql的形式查询
 * from Customer where custname = ?
 * 配置jpql语句 使用@Query
 */
@Query(value ="from Customer where custname = ?")
    public Customer  findjpql (String custName);
​
​
}

建立测试类:

public class jpqltext {
    @Autowired
    private CustomerDao customerDao;
@Test
    public  void  testfindjpql(){
    Customer customer = customerDao.findjpql("dade");
    System.out.println(customer);
}
}

需要注意的是:上面的参数只有一个,那么对于多个 占位符参数 赋值的时候,默认情况下 占位符的位置要和参数的位置保持一致 。

也可以用索引的方式来指定占位符的取值来源,如下图:

运行结果如下:说明我们的jpql查询成功了

jpql更新的操作:

编写dao层

使用jpql更新
根据id更新客户的名称,更新id为4的名称 将名称改为老尤。
sql:update  cst_customer set custname= ? where custid =?
jpql:update  Customer set custname =? where custid = ?
@Query  代表的是进行查询
而此方法我们还要声明这是更新的操作加上一个注解@Modifying:代表当前执行方法是一条更新语句
更新就不需要返回值了
@Query(value = "update  Customer set custname =?2 where custid = ?1")
@Modifying
public void updateCustomer (Integer id,String custname);
}

测试类:

注意这里要添加注解:@Transactional 更新/删除的操作必须添加事务的支持!

/**
 * 测试jpql的更新操作
 */
@Test
@Transactional//添加事务的支持
public  void  updatecustomer (){
    customerDao.updateCustomer(4,"老尤");
}

运行结果:

最后在表里发现并没有修改成功

原因:添加事务支持后 它会默认在执行结束后回滚事务,造成了一种执行成功的假象,所以会出现以下情况。

解决办法:使用 @Rollback(value = false) :设置是否自动回滚。

再运行:数据库修改成功

sql查询:

在新添加的方法上使用sql查询语句

注解@Query (value =“sql” , nativeQuery:false(使用jpql查询)ture:使用sql查询即本地查询)

dao层:

**
 * 使用sql查询
 * 查询全部
 * sql:select * from cst_customer ;
 * nativeQuery  true:sql查询  false:jpql查询
 * value:sql查询
 */
@Query(value= "select * from cst_customer" ,nativeQuery = true )
public List<Object[]> findsql ();
​
/**
 * sql模糊查询
 * sql:select *from  cst_customer where custname like ?
 */
@Query(value= "select * from  cst_customer where custname like ?1",nativeQuery = true )
public List<Object[]> findsqlmohu (String name);
}

测试:

    /**
     * sql查询
     */
    @Test
public void findsql (){
    List<Object[]> list = customerDao.findsql();
    for (Object[] obj:list ) {
        System.out.println(Arrays.toString(obj));
    }
}
    * sql查询 模糊
     */
    @Test
    public void findsqlmohu (){
        List<Object[]> list = customerDao.findsqlmohu("老尤");
        for (Object[] obj:list ) {
            System.out.println(Arrays.toString(obj));
        }
    }

方法名规则查询:

对jpql查询的封装

我们只需要按照springDataJpa提供的方法名称规则定义方法,不需要再去配置jpql语句完成查询

规则:findBy开头:代表查询

对象中的属性名称(首字母大写)

含义:根据属性名称进行查询

dao:

/**
 * 方法名的约定
 * findBy:查询(对象中的属性名首字母大写):查询条件
 * findByCustname 根据客户名称查询
 模糊查询只需要在后面加like   findByCustnameLike
 */
public Customer findByCustname (String custname);

测试:

/**
 * 测试方法命名规则的查询方法
 */
@Test
public void testfangfa(){
    Customer byCustname = customerDao.findByCustname("老尤");
    System.out.println(byCustname);
}

多条件查询:

findBy + 属性名 + 查询方式 + 多条件连接符(and/or)+ 属性名 + 查询方式

dao

多条件查询
 * findBy + 属性名 + 查询方式 + 多条件连接符(and/or)+ 属性名 + 查询方式
 *
 */
public Customer findByCustnameLikeAndCustindustry(String custname,String custindustry);

测试:

/**
 * 多条件查询测试
 */
@Test
public void findByCustnameLikeAndCustindustry(){
    Customer byCustnameLikeAndCustindustry = customerDao.findByCustnameLikeAndCustindustry("dade%", "程序员");
    System.out.println(byCustnameLikeAndCustindustry);
}

动态查询:JpaSpecificationExecutor方法列表

以上内容主要针对第一个接口进行查询,现在我们要对第二个接口进行查询。

首先概述一下这个接口的概念还有具体的查询方式:

T findone(Specification<T> spec);查询单个对象

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

Integer count (Specification<T> spec);统计查询

分页:

Page<T> findAll (Specification<T> spec,Pageable pageable);

Pageable:分页的参数

/**
     * 分页查询
     *  findAll (Specification<T> spec,Pageable pageable);有条件的分页
     *  spec:查询条件
     *  pageable:分页参数
     *   findAll (Pageable pageable)没有条件的分页
     */
    @Test
    public  void  specfengye(){
        Specification specification = null;//表示没有条件的分页
        //创建pagerequest对象
        /**
         * PageRequest对象是pageable接口的实现类
         * 里面有两个参数1.表示当前查询的页数(从0开始)
         *              2.每页查询几条数据
         */
        Pageable pageable = new PageRequest(0,2);//这里表示从第一条数据查询,每页显示两条数据
        Page<Customer> all = customerDao.findAll(null, pageable);
        System.out.println(all.getContent());//得到数据集合列表
        System.out.println(all.getTotalElements());//得到总条数
        System.out.println(all.getTotalPages());//得到总页数,即分的页数
    }
}

排序查询:

List <T> findAll (Specification<T> spec,Sort sort);

Sort:排序参数

 @Test
    public void specmohu() {
        Specification<Customer> spec = new Specification<Customer>() {
            @Override
            public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Path<Object> custname = root.get("custname");
                //查询方式模糊匹配
                //gt,lt,ge,le,like得到的path对象要指定参数类型才能再去比较
                //用.as去定义字段的类型
                Predicate like = cb.like(custname.as(String.class), "老尤%");
                return like;
            }
        };
        /**
         * 排序:1.创建排序对象,第一个参数:排序的顺序(倒序 desc   升序asc)
         *                             排序的属性名称
         */
        Sort sort = new Sort(Sort.Direction.DESC, "custid");
        List<Customer> all = customerDao.findAll(spec, sort);
        for (Customer customer : all) {
            System.out.println(customer);
        }
        
    }

以上内容的参数都有Specification,我们需要自己定义Specification的实现类

predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb);

root:查询的根对象

CriteriaQuery:自定义查询

CriteriaBuilder:查询的构造器(内部封装了很多查询条件)

接下来我们开始动态查询:

第一步首先搭建项目:和之前一样

第二部编写dao层接口 同上

第三步编写测试类:(有讲究了如下:)

自定义查询的条件

  • 1.实现Specification接口

  • 2.实现toPredicate方法 构造查询条件

  • 3.借助toPredicate方法参数中的两个参数:root:获取查询对象的属性

    CriteriaBuilder:构造查询条件:这个参数内部封装了许多查询条件

    具体如下:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class SpecTest {
    @Autowired
    private CustomerDao customerDao;
​
    /**
     * 查询单个对象  (动态查询)
     */
    @Test
    public  void testSpec(){
/**
 * 自定义查询的条件
 * 1.实现Specification接口
 * 2.实现toPredicate方法 构造查询条件
 * 3.借助toPredicate方法参数中的两个参数:root:获取查询对象的属性
 *                                   CriteriaBuilder:构造查询条件:这个参数内部封装了许多查询条件
 * 案例:根据客户名称查询 查询客户名称为dade的客户
 * 查询方式:CriteriaBuilder对象
 * 比较的属性名称:root对象 可以通过root对象获取想要比较的属性
 */
        Specification<Customer> spec  = new Specification<Customer>() {
​
            public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                //获取比较的属性,这里是客户名称
                Path<Object> custname = root.get("custname");
                //构造查询条件
                Predicate dade = cb.equal(custname, "dade");//进行精准匹配 第一个参数:需要比较的属性   第二个参数:需要比较的属性的值
​
                return dade;
            }
        };
        Customer one = customerDao.findOne(spec);
        System.out.println(one);
    }

多个条件查询:

用到连接符 and

@Test
public void Spec (){
    /**
     * 多条件查询
     * 案例:更具客户的名称和客户的行业进行查询  名称custname :老尤  行业 custindustry:大苏打
     */
    Specification<Customer> spec = new Specification<Customer>() {
        @Override
        public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            //获取比较的属性 名称custname :dade  行业 custindustry:jav
            Path<Object> custname = root.get("custname");
            Path<Object> custindustry = root.get("custindustry");
            //构造查询条件
            Predicate dede = cb.equal(custname, "老尤");
            Predicate dede1 = cb.equal(custindustry, "大苏打");
            //将多个条件连接在一起:and :以与的形式连接   or:以或的形式连接
            Predicate and = cb.and(dede,dede1);
​
            return and;
        }
    };
    Customer one1 = customerDao.findOne(spec);//什么时候用findone 和findAll 在数据库字段属性有多个相同的属性值是用findone
    System.out.println(one1);
}

模糊 查询:

/**
 * 模糊匹配
 * 根据客户名称模糊匹配 返回客户列表
 * 根据custname查询返回列表
 */
@Test
public void specmohu (){
    Specification<Customer> spec = new Specification<Customer>() {
        @Override
        public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            Path<Object> custname = root.get("custname");
            //查询方式模糊匹配
            //gt,lt,ge,le,like得到的path对象要指定参数类型才能再去比较
            //用.as去定义字段的类型
            Predicate like = cb.like(custname.as(String.class), "老尤%");
            return like;
        }
    };
    List<Customer> all = customerDao.findAll(spec);
    for (Customer c:all) {
        System.out.println(c);
    }
}

还有级联关系,jpa级联关系操作复杂,建议用mybatis,jpa适合单表查,搞完级联关系 啊啊啊,还不如用别的框架

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Data JPA 是一个用于简化数据库访问的框架,它基于 JPA (Java Persistence API) 规范,提供了一种更简单、更高效的方式来访问和操作数据库。 下面是使用 Spring Data JPA 的一般步骤: 1. 添加依赖:在你的项目中,添加 Spring Data JPA 的依赖。你可以在 Maven 或 Gradle 配置文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> ``` 2. 配置数据库连接:在 `application.properties` 或 `application.yml` 文件中配置数据库连接信息,包括数据库 URL、用户名、密码等。 3. 创建实体类:创建与数据库表对应的实体类,并使用 JPA 注解来映射实体类与数据库表之间的关系。 ```java @Entity @Table(name = "users") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private Integer age; // getters and setters } ``` 4. 创建 Repository 接口:创建一个继承自 `JpaRepository` 的接口,并通过方法命名规则或自定义查询方法来定义数据库操作。 ```java public interface UserRepository extends JpaRepository<User, Long> { List<User> findByAgeGreaterThan(Integer age); } ``` 5. 使用 Repository:在需要访问数据库的地方,注入 Repository 接口,并调用其中的方法进行数据库操作。 ```java @Service public class UserService { @Autowired private UserRepository userRepository; public List<User> getUsersByAgeGreaterThan(Integer age) { return userRepository.findByAgeGreaterThan(age); } } ``` 这只是 Spring Data JPA 的基本用法,你还可以使用更高级的特性,如分页、排序、复杂查询等。希望这些信息对你有帮助!如果你有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值