智销系统项目day1 - 基础配置和SpringDataJpa

文章目录

  • 1. 创建项目的基础配置
    • 1.1 引入项目中所需要的所有包(pom.xml)
    • 1.2 配置applicationContext.xml文件
    • 1.3 准备Domain
    • 1.4 完成Repository的功能
    • 1.5 测试集成是否成功
  • 2. JpaSpecificationExecutor认识
    • 2.1 单个条件的查询
    • 2.2 多个条件查询
    • 2.3 查询+分页+排序
  • 3. spec插件
    • 3.1 功能介绍
  • 3.2 在Maven中引入相应的包
    • 3.3 功能测试
      • 3.3.1 单个条件查询
      • 3.3.2 多个条件查询
      • 3.3.3 条件+排序分页功能
  • 4. Query查询条件
    • 4.1 BaseQuery:公共的分页条件
    • 4.2 EmployeeQuery:Employee特有的一些条件
    • 4.3 功能测试

1. 创建项目的基础配置

1.1 引入项目中所需要的所有包(pom.xml)


<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.0modelVersion>

  <groupId>cn.itsourcegroupId>
  <artifactId>yxbartifactId>
  <version>1.0-SNAPSHOTversion>

  <properties>
    <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    <org.springframework.version>4.2.5.RELEASEorg.springframework.version>
    <org.hibernate.version>4.3.8.Finalorg.hibernate.version>
    <spring-data-jpa.version>1.9.0.RELEASEspring-data-jpa.version>
    <com.fasterxml.jackson.version>2.5.0com.fasterxml.jackson.version>
    <org.slf4j.version>1.6.1org.slf4j.version>
  properties>
  <dependencies>
    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-coreartifactId>
      <version>${org.springframework.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-contextartifactId>
      <version>${org.springframework.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-context-supportartifactId>
      <version>${org.springframework.version}version>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-txartifactId>
      <version>${org.springframework.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-jdbcartifactId>
      <version>${org.springframework.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-ormartifactId>
      <version>${org.springframework.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-aopartifactId>
      <version>${org.springframework.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-testartifactId>
      <version>${org.springframework.version}version>
      <scope>testscope>
    dependency>
    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webartifactId>
      <version>${org.springframework.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webmvcartifactId>
      <version>${org.springframework.version}version>
    dependency>
    
    <dependency>
      <groupId>org.apache.commonsgroupId>
      <artifactId>commons-ioartifactId>
      <version>1.3.2version>
    dependency>
    
    <dependency>
      <groupId>commons-fileuploadgroupId>
      <artifactId>commons-fileuploadartifactId>
      <version>1.2.2version>
    dependency>
    
    <dependency>
      <groupId>com.fasterxml.jackson.coregroupId>
      <artifactId>jackson-coreartifactId>
      <version>${com.fasterxml.jackson.version}version>
    dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.coregroupId>
      <artifactId>jackson-annotationsartifactId>
      <version>${com.fasterxml.jackson.version}version>
    dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.coregroupId>
      <artifactId>jackson-databindartifactId>
      <version>${com.fasterxml.jackson.version}version>
    dependency>
    
    <dependency>
      <groupId>org.hibernategroupId>
      <artifactId>hibernate-coreartifactId>
      <version>${org.hibernate.version}version>
    dependency>
    <dependency>
      <groupId>org.hibernategroupId>
      <artifactId>hibernate-entitymanagerartifactId>
      <version>${org.hibernate.version}version>
    dependency>
    
    <dependency>
      <groupId>org.springframework.datagroupId>
      <artifactId>spring-data-jpaartifactId>
      <version>${spring-data-jpa.version}version>
    dependency>
    
    <dependency>
      <groupId>com.github.wenhaogroupId>
      <artifactId>jpa-specartifactId>
      <version>3.1.1version>
      
      <exclusions>
        <exclusion>
          <groupId>*groupId>
          <artifactId>*artifactId>
        exclusion>
      exclusions>
    dependency>

    <dependency>
      <groupId>commons-dbcpgroupId>
      <artifactId>commons-dbcpartifactId>
      <version>1.2.2version>
    dependency>

    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>5.1.6version>
    dependency>

    <dependency>
      <groupId>org.apache.commonsgroupId>
      <artifactId>commons-lang3artifactId>
      <version>3.5version>
    dependency>
    
    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>4.12version>
      <scope>testscope>
    dependency>
    <dependency>
      <groupId>javax.servletgroupId>
      <artifactId>javax.servlet-apiartifactId>
      <version>3.1.0version>
      
      <scope>providedscope>
    dependency>
    
    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>slf4j-apiartifactId>
      <version>${org.slf4j.version}version>
    dependency>
    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>slf4j-log4j12artifactId>
      <version>${org.slf4j.version}version>
      <scope>runtimescope>
    dependency>
    <dependency>
      <groupId>log4jgroupId>
      <artifactId>log4jartifactId>
      <version>1.2.14version>
    dependency>
    
    <dependency>
      <groupId>org.apache.velocitygroupId>
      <artifactId>velocityartifactId>
      <version>1.6version>
    dependency>
  
   <dependency>
      <groupId>org.apache.shirogroupId>
      <artifactId>shiro-allartifactId>
      <version>1.4.0version>
      <type>pomtype>
  dependency>
    
    <dependency>
      <groupId>org.apache.shirogroupId>
      <artifactId>shiro-springartifactId>
      <version>1.4.0version>
    dependency>
    
    <dependency>
      <groupId>org.apache.poigroupId>
      <artifactId>poiartifactId>
      <version>3.11version>
    dependency>
    <dependency>
      <groupId>org.apache.poigroupId>
      <artifactId>poi-ooxmlartifactId>
      <version>3.11version>
    dependency>
    
    
    <dependency>
      <groupId>net.coobirdgroupId>
      <artifactId>thumbnailatorartifactId>
      <version>0.4.6version>
    dependency>
    
    <dependency>
      <groupId>quartzgroupId>
      <artifactId>quartzartifactId>
      <version>1.5.2version>
    dependency>
    
    <dependency>
      <groupId>javax.mailgroupId>
      <artifactId>mailartifactId>
      <version>1.4.1version>
    dependency>
  dependencies>

  <build>
    <finalName>yxbfinalName>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.pluginsgroupId>
        <artifactId>maven-compiler-pluginartifactId>
        <configuration>
          <source>1.8source>
          <target>1.8target>
        configuration>
      plugin>
      <plugin>
        <groupId>org.mortbay.jettygroupId>
        <artifactId>jetty-maven-pluginartifactId>
        <version>8.1.15.v20140411version>
        <configuration>
          <stopPort>9966stopPort>
          <stopKey>foostopKey>
          <webAppConfig>
            <contextPath>/contextPath>
          webAppConfig>
        configuration>
      plugin>
    plugins>
  build>
project>

1.2 配置applicationContext.xml文件

注意:修改相应的包扫描(每个系统都会有不一样的地方)
里面的路径需要注意不要配错,建表策略为false


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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"
       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
         http://www.springframework.org/schema/data/jpa
         http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

    
    <context:component-scan base-package="com.zpx.domain" />
    <context:property-placeholder location="classpath:jdbc.properties" />

    
    <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}" />
        
        <property name="maxActive" value="150" />
        
        <property name="minIdle" value="5" />
        
        <property name="maxIdle" value="20" />
        
        <property name="initialSize" value="30" />
        
        
        <property name="logAbandoned" value="true" />
        
        <property name="removeAbandoned" value="true" />
        
        <property name="removeAbandonedTimeout" value="10" />
        
        <property name="maxWait" value="1000" />
        
        <property name="timeBetweenEvictionRunsMillis" value="10000" />
        
        <property name="numTestsPerEvictionRun" value="10" />
        
        <property name="minEvictableIdleTimeMillis" value="10000" />
        <property name="validationQuery" value="SELECT NOW() FROM DUAL" />
    bean>

    
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        
        <property name="packagesToScan" value="com.zpx.domain" />
        
        
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                
                
                <property name="showSql" value="true" />
                
                <property name="generateDdl" value="false" />
                
                <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
            bean>
        property>
    bean>

    
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    bean>
    
    <tx:annotation-driven />

    
    
    <jpa:repositories base-package="com.zpx.repository" transaction-manager-ref="transactionManager"
                      entity-manager-factory-ref="entityManagerFactory" />
beans>

1.3 准备Domain

父类:BaseDomain

package com.zpx.domain;

import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
//MappedSuperclass:表示当前类是父类
@MappedSuperclass
// 在JPA里面就表示是父类,不持久化到表
public class BaseDomain {
    @Id
    @GeneratedValue
    protected Long id;
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
}

子类Employee

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

    private String username;
    private String password;
    private String email; 
    private Integer age;
   //省略getter,setter与toString(注意:Alt+Insert可以自动生成)
}

1.4 完成Repository的功能

package com.zpx.repository;

import com.zpx.domain.Employee;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * 必需继续JpaRepository<1v,2v>
 *     1v:代表你要操作的是哪一个domain对象
 *     2v:这个domain对象的主键的类型
 */
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}

1.5 测试集成是否成功

package com.zpx.repository;

import com.zpx.domain.Employee;
...
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class EmployeeRepositoryTest  {
    @Autowired
    private EmployeeRepository employeeRepository;
    @Test
    public void testFind() throws Exception{
        List<Employee> emps = employeeRepository.findAll();
        for (Employee emp :emps){
            System.out.println(emp);
        }
    }
}

2. JpaSpecificationExecutor认识

  • JpaSpecificationExecutor(JPA规则执行者)是JPA2.0提供的Criteria API的使用封装,可以用于动态生成Query来满足我们业务中的各种复杂场景。
  • Spring Data JPA为我们提供了JpaSpecificationExecutor接口,只要简单实现toPredicate方法就可以实现复杂的查询。
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);
}

我们要使用这个接口中的方法,首先让我们的接口也去继承这个接口:

public interface EmployeeRepository extends JpaRepository<Employee,Long>,JpaSpecificationExecutor<Employee> { }

2.1 单个条件的查询

@Test
public void testJpaSpecificationExecutor()throws Exception{
     /*
     根据相应的规则(Specification),查询对应的数据
     Predicate:where xxx=? and yyy=?
     root:根,可以获取到类中的属性(xxx,yyy...)
     CriteriaQuery:查询哪些字段,排序是什么(主要是把多个查询的条件连系起来)
     CriteriaBuilder:字段之间是什么关系,如何生成一个查询条件,每一个查询条件都是什么方式
                      主要判断关系(和这个字段是相等,大于,小于like等)

     */
     List<Employee> list = employeeRepository.findAll(new Specification<Employee>() {
         @Override
         public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
             //使用root拿到相应的username属性
             Path usernamePath = root.get("username");
             //为属性添加查询规则
             Predicate predicate = cb.like(usernamePath, "%1%");
             return predicate;
         }
     });
     list.forEach(e-> System.out.println(e));
 }

2.2 多个条件查询

@Test
public void testJpaSpecificationExecutor02()throws Exception{

    List<Employee> list = employeeRepository.findAll(new Specification<Employee>() {
        @Override
        public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
            //使用root拿到相应的username属性
            Path usernamePath = root.get("username");
            //为属性添加查询规则
            Predicate p1 = cb.like(usernamePath, "%1%");
            Path emailPath = root.get("email");
            Predicate p2 = cb.like(emailPath, "%2%");
            //gt大于的意思
            Path agePath = root.get("age");
            Predicate p3 = cb.gt(agePath, 20);
            //多个条件连接起来
            Predicate predicate = cb.and(p1, p2, p3);
            return predicate;
        }
    });
    list.forEach(e-> System.out.println(e));
}

2.3 查询+分页+排序

@Test
    public void testJpaSpecificationExecutor03()throws Exception{
        Pageable pageable = new PageRequest(0,10);
        Sort sort = new Sort(Sort.Direction.DESC,"age");

        Page<Employee> page = employeeRepository.findAll(new Specification<Employee>() {
            @Override
            public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                //使用root拿到相应的username属性
                Path usernamePath = root.get("username");
                //为属性添加查询规则
                Predicate predicate = cb.like(usernamePath, "%1%");

                return predicate;
            }
        }, pageable);
        page.forEach(e-> System.out.println(e));
    }

3. spec插件

这是一个对于咱们刚才的动态生成Query功能的一个封装版,如果我们使用这个插件,在完成查询与分页的时候功能会简单不少。
基于Spring Data Jpa的动态查询库 https://github.com/wenhao/jpa-spec

3.1 功能介绍

  1. 兼容Spring Data Jpa 和JPA2.1接口。
  2. Equal/NotEqual/Like/NotLike/In/NotIn支持可变参数, Equal/NotEqual 支持空(Null)值。
  3. 每个条件支持关联查询。
  4. 支持自定义条件查询。
  5. 条件构建器。
  6. 支持分页和排序。

3.2 在Maven中引入相应的包

pom.xml(咱们项目中已经引入):


<dependency>
  <groupId>com.github.wenhaogroupId>
  <artifactId>jpa-specartifactId>
  <version>3.1.1version>
  
  <exclusions>
    <exclusion>
      <groupId>*groupId>
      <artifactId>*artifactId>
    exclusion>
  exclusions>
dependency>

3.3 功能测试

3.3.1 单个条件查询

@Test
public void testJpaSpac01()throws Exception{
    //导包注意导入wenhao的包
    //获取到查询的规则
    Specification<Employee> spec = Specifications.<Employee>and()
            .like("username","%1%")
            .build();
    //根据规则完成查询
    List<Employee> list = employeeRepository.findAll(spec);
    list.forEach(e-> System.out.println(e));
}

3.3.2 多个条件查询

@Test
public void testJpaSpec02()throws Exception{
     //获取到查询的规则
     Specification<Employee> spec = Specifications.<Employee>and()
             .like("username", "%1%")
             .like("email","%2%")
             .gt("age",20)
             .build();
     //根据规则完成查询
     List<Employee> list = employeeRepository.findAll(spec);
     list.forEach(e-> System.out.println(e));
 }

3.3.3 条件+排序分页功能

@Test
public void testJpaSpac03()throws Exception{
     //先获取分页和排序对象
     Sort sort = new Sort(Sort.Direction.valueOf("DESC"),"age");
     Pageable pageable = new PageRequest(0,10,sort);
     //导包注意导入wenhao的包
     //获取到查询的规则
     Specification<Employee> spec = Specifications.<Employee>and()
             .like("username","%1%")
//              .like("email","%2%")
//             .gt("age",20)
             .build();
     //根据规则完成查询
     Page<Employee> page = employeeRepository.findAll(spec, pageable);

     page.forEach(e-> System.out.println(e));
 }

Jpa-spec的功能还是比较简单实用的。其它一些功能,我们在项目用到再说相应的讲解。大家也可以去参照网络上相就的中文文档:
https://github.com/wenhao/jpa-spec/blob/master/docs/3.1.0_cn.md
https://www.w3cschool.cn/jpaspec/

4. Query查询条件

咱们每一个项目是做过高级查询与分页的,大家应该都清楚,查询的数据是从前端由客户输入(或者选择)传到后台的。那么,我们需要注意的情况有哪些呢?

  1. 用户传的数据有0-n个(我们需要去判断)
  2. 咱们必需要准备一个对象接收用户传过来的数据(使用Query对象)
  3. 分页的条件对我们来说也是封装到Query对象中的
    接下来,我们要准备我们的Query对象:

4.1 BaseQuery:公共的分页条件

public abstract class BaseQuery {
    //当前页
    private int currentPage = 1;
    //每条条数
    private int pageSize = 10;
    //排序字段名(如果前台没有传字段名,代表不需要做排序)
    private String orderName;
    //排序的规则
    private String orderType = "ASC";
    //写个抽象方法去规范子类获取Specification对象的名称必需叫:createSpec
    public abstract Specification createSpec();
    //创建排序对象
    public Sort createSort(){
        if(StringUtils.isNotBlank(orderName)){
            //toUpperCase() 方法用于把字符串转换为大写。
            return new Sort(Sort.Direction.valueOf(orderType.toUpperCase()),orderName);
        }
        return null;
    }
    public int getCurrentPage() {
        return currentPage;
    }
    //第一页从0开始计算
    public int getJpaCurrentPage() {
        return currentPage-1;
    }
    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }
    public int getPageSize() {
        return pageSize;
    }
    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }
    public String getOrderName() {
        return orderName;
    }
    public void setOrderName(String orderName) {
        this.orderName = orderName;
    }
    public String getOrderType() {
        return orderType;
    }
    public void setOrderType(String orderType) {
        this.orderType = orderType;
    }
}

4.2 EmployeeQuery:Employee特有的一些条件

public class EmployeeQuery extends BaseQuery {
    private String username;
    private String email;
    private Integer age;
    //返回咱们的查询条件 where username = ?
    @Override
    public Specification createSpec(){
        /**
         * like方法两个参数
         *  1.查询的字段
         *  2.这个字段条件对应的值
         * like方法三个参数
         *  1.boolean false,这个查询不执行
         *  2.查询的字段
         *  3.这个字段条件对应的值
         */
         //抽取spac
        Specification<Employee> spec = Specifications.<Employee>and()
                .like(StringUtils.isNotBlank(username),"username", "%"+username+"%")
                .like(StringUtils.isNotBlank(email),"email", "%"+email+"%")
                .gt(age!=null,"age", age)
                .build();
        return spec;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
}

4.3 功能测试

//wendao抽取的查询并分页功能
    @Test
    public void testJpaSpecPageQuery()throws Exception{
        EmployeeQuery query = new EmployeeQuery();
        query.setUsername("1");
        query.setOrderName("age");
        query.setOrderType("DESC");
        //调用被抽取的查询方法,拿到对象
        Specification spec = query.createSpec();
        //调用被抽取的分页方法,拿到对象
        Sort sort = query.createSort();
        //用sort创建page对象,并封装
        Pageable pageable = new PageRequest(query.getJpaCurrentPage(), query.getPageSize(), sort);
        //查询全部,传入对象
        Page<Employee> page = employeeRepository.findAll(spec, pageable);
        page.forEach(e-> System.out.println(e));
    }

你可能感兴趣的:(java)