SpringDataJpa

Posted ruijiege

tags:

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

一.什么是SpringDataJpa

 

一.什么是SpringDataJpa

  • 它是Spring的一个子框架
  • 集成Jpa,让咱们操作数据库变得更加的简单

二.项目导包

  • 能够看懂这里导入了哪些包
  • 也可以理解这些包是做什么的
<?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>cn.itsource</groupId>
  <artifactId>aisell</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>aisell Maven Webapp</name>
  <!-- FIXME change it to the project\'s website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <org.springframework.version>4.2.5.RELEASE</org.springframework.version>
    <org.hibernate.version>4.3.8.Final</org.hibernate.version>
    <spring-data-jpa.version>1.9.0.RELEASE</spring-data-jpa.version>
    <com.fasterxml.jackson.version>2.5.0</com.fasterxml.jackson.version>
    <org.slf4j.version>1.6.1</org.slf4j.version>
  </properties>
  <dependencies>
    <!-- Spring的支持包 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <!-- 上下文支持包(帮我们集成:模板,邮件,任务调度...) -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${org.springframework.version}</version>
      <scope>test</scope>
    </dependency>
    <!-- 引入web前端的支持 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <!-- SpringMCV上传需要用到io包-->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-io</artifactId>
      <version>1.3.2</version>
    </dependency>
    <!-- 文件上传用到的包 -->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.2.2</version>
    </dependency>
    <!-- SpringMVC的json支持包 -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>${com.fasterxml.jackson.version}</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>${com.fasterxml.jackson.version}</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>${com.fasterxml.jackson.version}</version>
    </dependency>
    <!-- hibernate的支持包 -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>${org.hibernate.version}</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>${org.hibernate.version}</version>
    </dependency>
    <!-- SpringDataJpa的支持包 -->
    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-jpa</artifactId>
      <version>${spring-data-jpa.version}</version>
    </dependency>
    <!-- SpringData的擴展包 -->
    <dependency>
      <groupId>com.github.wenhao</groupId>
      <artifactId>jpa-spec</artifactId>
      <version>3.1.1</version>
      <!-- 把所有的依賴都去掉 -->
      <exclusions>
        <exclusion>
          <groupId>*</groupId>
          <artifactId>*</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.2.2</version>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.6</version>
    </dependency>
    <!--lang3:工具包 java.lang.-->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.5</version>
    </dependency>
    <!-- 測試包 -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <!-- 这个scope 只能作用在编译和测试时,同时没有传递性。表示在运行的时候不添加此jar文件 -->
      <scope>provided</scope>
    </dependency>
    <!-- 日志文件 -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${org.slf4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${org.slf4j.version}</version>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.14</version>
    </dependency>
    <!-- 代码生成器模版技术  -->
    <dependency>
      <groupId>org.apache.velocity</groupId>
      <artifactId>velocity</artifactId>
      <version>1.6</version>
    </dependency>
    <!-- shiro(权限框架)的支持包 -->
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-all</artifactId>
      <version>1.4.0</version>
      <type>pom</type>
    </dependency>
    <!-- shiro与Spring的集成包 -->
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-spring</artifactId>
      <version>1.4.0</version>
    </dependency>
    <!-- poi(操作办公软件)支持的jar包 -->
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
      <version>3.11</version>
    </dependency>
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
      <version>3.11</version>
    </dependency>
    <!-- 图片压缩功能 -->
    <!-- 缩略图 -->
    <dependency>
      <groupId>net.coobird</groupId>
      <artifactId>thumbnailator</artifactId>
      <version>0.4.6</version>
    </dependency>
    <!-- 定时调度 -->
    <dependency>
      <groupId>quartz</groupId>
      <artifactId>quartz</artifactId>
      <version>1.5.2</version>
    </dependency>
    <!-- 邮件支持 -->
    <dependency>
      <groupId>javax.mail</groupId>
      <artifactId>mail</artifactId>
      <version>1.4.1</version>
    </dependency>
  </dependencies>

  <build>
    <finalName>aisell</finalName>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>jetty-maven-plugin</artifactId>
        <version>8.1.15.v20140411</version>
        <configuration>
          <stopPort>9966</stopPort>
          <stopKey>foo</stopKey>
          <webAppConfig>
            <contextPath>/</contextPath>
          </webAppConfig>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

三 集成SpringDataJpa

3.1 完成Spring与Jpa的集成

昨天已经详细讲解过(要求自己是可以把它写出来)

3.1.1 准备db.propeties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///aisell
jdbc.username=root
jdbc.password=123456

3.2.2 准备applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
">
    <!--扫描service层的类-->
    <context:component-scan base-package="cn.itsource.aisell.service" />
    <!--
        db.properties -> dataSource(配置数据源[连接池dbcp]) -> EntityManagerFactory -> dao -> service
            -> 事务 -> controller(集成SpringMVC) -> easyui
    -->
    <!--1.读取db.properties, 注意:不要忘了加classpath-->
    <context:property-placeholder location="classpath:db.properties" />
    <!--2.配置dbcp连接池-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>
    <!--
        JPA:ORM规范  -> 很多框架实现了这个规范(hibernate,openjpa,toplink,...)
        3.配置EntityManagerFactory对象
            3.1 基本配置都是写在Spring中(四大金刚,建表策略,方言,是否显示SQL)
            3.2 Spring来创建这个对象(准备一个domain,如果运行的时候创建了表,就代表这个对象是成功的)
            alt+insert -> JPA -> LocalContainerEntityManagerFactoryBean
            ctrl+t/f4 : 有办法看结构
    -->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--扫描JPA支持的注解-->
        <property name="packagesToScan" value="cn.itsource.aisell.domain" />
        <!--
            告诉Spring我们使用的是哪一个框架来完成JPA规范
            这里就需要我们配置一个适配器
            jpaVendorAdapter:JPA需要配置的适配器(我们会选择hibernate)
        -->
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <!--方言-->
                <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
                <!--
                    建表策略
                -->
                <property name="generateDdl" value="false" />
                <!--是否显示sql-->
                <property name="showSql" value="true" />
            </bean>
        </property>
    </bean>
    <!--4.加上事务-->
    <!--4.1 准备事务管理器-->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>
    <!--4.2 开启(注解)事务支持-->
    <tx:annotation-driven transaction-manager="transactionManager" />

</beans>

3.2 集成SpringDataJpa

3.2.1 准备domain(父类)

  1. BaseDomain

jpa中父类domain必需要加上:@MappedSuperclass

/**
 * 泛化:继承关系
 * 在我们JPA,如果要抽取一个父类,就必需加上 @MappedSuperclass
 *  非常明确定的告诉JPA,这是一个用于映射的父类
 */
@MappedSuperclass
public class BaseDomain {
    @Id
    @GeneratedValue
    protected Long id;

   //getter,setter ...
}
  1. Employeee

@Entity
@Table(name = "employee")
public class Employee extends BaseDomain {

    private String username;
    private String password;
    private Integer age;
    private String email;
    //getter,setter ...
   
}

3.2.2 准备Repository接口

/**
 * 关于Employee对象的CRUD(分页排序) 就写完了
 *  泛型一:对哪一个实体做CRUD
 *  泛型二:主键的类型
 */
public interface EmployeeRepository extends JpaRepository<Employee,Long> {
    ...
}

3.2.3 扫描repository

  • repository 就是咱们过去的dao
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      ...
       xmlns:jpa="http://www.springframework.org/schema/data/jpa"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
      ...
      http://www.springframework.org/schema/data/jpa
      http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
">
   ...

    <!-- 让SpringDataJpa去扫描repository -->
    <jpa:repositories base-package="cn.itsource.aisell.repository"
                      entity-manager-factory-ref="entityManagerFactory"
                      transaction-manager-ref="transactionManager" />

</beans>

四.完成的CRUD功能

4.1 基本的CRUD

  • 查询所有:employeeRepository.findAll()
  • 查询一条数据: employeeRepository.findOne(1L)
    • 思考题: findOne与getOne的区别?
  • 添加/修改: employeeRepository.save(employee)
    • 主要看数据库中是否有这个值
  • 删除 : employeeRepository.delete(274L)

4.2 分页和排序

4.2.1 排序

 /**
 * 排序对象
 *  第一个参数:排序的类型(升序还是降序)
 *  第二个参数:排序的属性
 */
Sort sort = new Sort(Sort.Direction.DESC,"age");

List<Employee> list = employeeRepository.findAll(sort);
list.forEach(e-> System.out.println(e));

4.2.2 分页

注:这里的分页是从0开始的

/**
 * page:第几页(0就是第1页)
 * size:每页条数
 */
Pageable pageable = new PageRequest(0,10);
//分页对象
Page<Employee> list = employeeRepository.findAll(pageable);

list.forEach(e-> System.out.println(e));

4.2.3 分页+排序

Sort sort = new Sort(Sort.Direction.DESC,"age");
/**
 * page:第几页(0就是第1页)
 * size:每页条数
 * sort:排序对象
 */
Pageable pageable = new PageRequest(0,10,sort);
//分页对象
Page<Employee> list = employeeRepository.findAll(pageable);

list.forEach(e-> System.out.println(e));

4.3 名称规则(根据条件进行查询)

详细规则请查看文档

/**
 * 根据规范(SpringDataJpa)写方法名,就可以进行查询
 * @param username
 * @return
 *  username =?
 */
//根据用户名查询一个员工
Employee findByUsername(String username);

//用户名模糊查询 username like ?
List<Employee> findByUsernameLike(String username);

//用户名与邮件模糊查询 username like ? and email like ?
List<Employee> findByUsernameLikeAndEmailLike(String username,String email);

4.4 Query注解查询

//根据用户名获取用户
@Query("select o from Employee o where o.username =?1")
Employee query01(String username);

//用户名与邮件模糊查询 username like ? and email like ?
@Query("select o from Employee o where o.username  like ?1 and o.email like ?2")
List<Employee> query02(String username,String email);
//    @Query("select o from Employee o where o.username  like :username and o.email like :email")
//    List<Employee> query02(@Param("username") String username,@Param("email")  String email);

//直接写原生的SQL
@Query(nativeQuery=true,value="select * from employee")
List<Employee> query03();

五.JpaSpecificationExecutor

  • 是一个JPA的规范执行者
  • JPA2.0提供的Criteria API的使用封装
  • 需要咱们的的repository继承JpaSpecificationExecutor接口
interface EmployeeRepository extends JpaRepository<Employee,Long>,JpaSpecificationExecutor<Employee>

5.1 最简单的查询

@Test
public void testJpaSpecificationExecutor01() throws Exception{
    /**
     * 这里的查询我们需要自己去定义规则:Specification
     */
    List<Employee> list = employeeRepository.findAll(new Specification<Employee>() {
        /**
         * 这个方法就是帮咱们创建规则的方法,只要把这个方法搞定,咱们就可以完成查询了
         * @param root(根) : 代表了可以查询和操作的实体对象的根
         *                可以帮助我们获取到实体对应的字段
         * @param query(查询) : 代表一个specific的顶层查询对象
         *                 包含查询的各个部分,比如select,from,where,group by ,order by 等
         *                  还可以支持and ,or的功能
         * @param cb :用来构建CriteriaQuery的构建器对象(相当于条件或者说条件组合)
         *                  主要判断关系(和这个字段是相等,大于,小于like等)
         *                  支持 and,or的功能
         * @return Predicate:表明; 阐明; 断言
         *          你把它当成  where username like ? and email like ? and age > ? ...
         */
        @Override
        public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            //1.拿到Employee中的username字段
            Path usernamePath = root.get("username");
            //2.加上字段的判断关系
            // 参数1:字段(以上是关于SpringDataJpa的主要内容,如果未能解决你的问题,请参考以下文章

SpringDataJpa

SpringBoot实战SpringDataJPA

SpringDataJpa

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

Spring Data JPA入门

15 Spring Data JPA概述