AIsell智能销售第一天SpringledataJpa

1.创建maven项目

(1)项目所有导包

<?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>yxb</artifactId>
  <version>1.0-SNAPSHOT</version>

  <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>
    <!-- SpringData的支持包 -->
    <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>

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

(2)考入资源配置.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns: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">
    <!-- 扫描spring service注解 repostory注解-->
    <context:component-scan base-package="cn.itsource.aisell"></context:component-scan>
    <!--jdbc.properties dataSource EntityManagerFactory Transaction-->
    <!-- 加载配置jdbc.properties-->
    <context:property-placeholder location="classpath:jdbc.properties" file-encoding="utf-8"/>
    <!-- 配置连接池dataSource bean生命周期方法 销毁方法close 用来连接之后 还给链接池-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
    <!-- 得到EntityManagerFactory 方言 链接池-->
    <!-- 得到EntityManagerFactory-->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">

        <!-- 配置属性 setDataSource-->
        <property name="dataSource" ref="dataSource"></property>
        <!-- 扫描实体类的配置 entity-->
        <property name="packagesToScan" value="cn.itsource.aisell.domain"></property>

        <property name="jpaVendorAdapter" >
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <!-- 是否显示sql-->
                <property name="showSql" value="true"></property>
                <!-- 是否创建表-->
                <property name="generateDdl" value="true"></property>
                <!--数据库方言-->
                <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"></property>
            </bean>
        </property>

    </bean>

    <!-- 事务管理器-->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"></property>
    </bean>

    <!-- 开启事务 扫描@Transaction这种注解-->
    <tx:annotation-driven/>
    <!-- Spring Data Jpa配置 ********************************************-->
    <!-- base-package:扫描的包 -->
    <jpa:repositories base-package="cn.itsource.aisell.repository" transaction-manager-ref="transactionManager"
                      entity-manager-factory-ref="entityManagerFactory" />


</beans>

(3)创建连接池配置文件一级创建domain,repository

(4)导图sql语句,抽取公共domainbase配置注解@mappedsuperclass(不创建数据库表)

(5)springdatejpa底层结构

 

 

(6)继承接口jpareposetory

(7)测试jpareposetory的crud

package cn.itsource.aisell;

import cn.itsource.aisell.domain.Employee;
import cn.itsource.aisell.repository.EmployeeRepository;
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.Sort;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestQuery {
//jparepository的基本crud
@Autowired
private EmployeeRepository employeeRepository;

@Test
//查询所有
public void test() throws Exception {
List<Employee> list = employeeRepository.findAll();
for (Employee employee : list) {
System.out.println(employee);
}

}

@Test
//查询一条
public void test2() throws Exception {
Employee employee = employeeRepository.findOne(1l);
System.out.println(employee);
}
@Test//增加
public void test3() throws Exception {
Employee employee = new Employee();
//log4j:WARN No appenders could be found for logger (org.springframework.test.context.junit4.SpringJUnit4ClassRunner).
//log4j:WARN Please initialize the log4j system properly.
employee.setUsername("小顺");
employee.setPassword("123");
employeeRepository.save(employee);
Employee employee2 = new Employee();
employee2.setUsername("小郑波");
employee2.setPassword("123");
employeeRepository.save(employee2);
}

@Test//删除
public void test4() throws Exception {
employeeRepository.delete(277L);
}

@Test//查询总数居条数
public void test5() throws Exception {
long count = employeeRepository.count();
System.out.println(count);
}

@Test
public void testPage() throws Exception {
PageRequest pageRequest = new PageRequest(0, 10);
Page<Employee> page = employeeRepository.findAll(pageRequest);
System.out.println("总页数:" + page.getTotalPages());
System.out.println("总条数:" + page.getTotalElements());
System.out.println("当前页的数据" + page.getContent());
System.out.println("当前第几页" + page.getNumber());
System.out.println("当前页的几条数据" + page.getNumberOfElements());//一般最后一页数据不等于每页的条数
System.out.println("每页的条数:" + page.getSize()); //每页条数
}

@Test
public void testPageandSort() throws Exception {
//准备一个排序对象
Sort sort = new Sort(Sort.Direction.DESC, "username");
//第一个参数是顺序,第二个是依据排序的字段
//准备一个page对象
PageRequest pageRequest = new PageRequest(0, 10, sort);
Page<Employee> page = employeeRepository.findAll(pageRequest);
for (Employee employee : page) {
System.out.println(employee);
}
}

//按照规范查询
@Test
public void testQuery() throws Exception {
List<Employee> employees = employeeRepository.findEmployeeByUsernameLike("a");
for (Employee employee : employees) {
System.out.println(employee);
}
}

//按照规范查询
@Test
public void testQuery1() throws Exception {
List<Employee> employees = employeeRepository.findEmployeeByUsername("%a%");
for (Employee employee : employees) {
System.out.println(employee);
}
}

//Query注解查询
@Test
public void testQuery2() throws Exception {
List<Employee> emps = employeeRepository.findEmpByUsername("%b%");
for (Employee emp : emps) {
System.out.println(emp);
}
}

//根据顺序来查询
@Test
public void testQuery3() throws Exception {
List<Employee> emps = employeeRepository.query02("%b%", "%2%");
for (Employee emp : emps) {
System.out.println(emp);
}
}
}

(8)条件查询和注解查询
package cn.itsource.aisell.repository;

import cn.itsource.aisell.domain.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

//Employee:代表你要操作的是哪一个domain对象
//Long:这个domain对象的主键的类型
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
//根据名称模糊查询
List<Employee> findEmployeeByUsernameLike(String username);
//根据名称进行查询
List<Employee> findEmployeeByUsername(String username);
//查询数据--Query注解查询
@Query("select o from Employee o where o.username like ?1 ")
List<Employee> findEmpByUsername(String username);

//根据顺序查询
@Query("select o from Employee o where o.username like ?1 and o.email like ?2")
List<Employee> query02(String username1,String email1);

//根据名称来查询
@Query("select o from Employee o where o.username like :username and o.email like :email")
List<Employee> query03(@Param("username") String username1, @Param("email")String email1);

//对原生sql语句
@Query(value="select count(*) from employee ",nativeQuery=true)
Long query04();
}



2.
jpa-spec插件
(1)条件加分页组合查询
//条件集成+分页
@Test
public void testSpecFind03() {
    Specification<Employee> spec = Specifications.<Employee>and().like("username", "%1%").build();
    //排序 :第一个参数是排序的规则(DESC/ASC)  后面参数是排序的字符
    Sort sort = new Sort(Sort.Direction.DESC,"username");
    Pageable pageable = new PageRequest(0, 10,sort);

    Page<Employee> page = employeeRepository.findAll(spec, pageable);
    for (Employee emp : page) {
        System.out.println(emp);
    }
}

 

(2)query查询,提取抽象具类,继承抽象类
抽象类
package cn.itsource.aisell.query;

import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;

public abstract class BaseQuery {
private Integer currentPage=1;
private Integer pageSize=10;
private String orderByName;
private String orderBuType="DESC";

public Integer getCurrentPage() {
return currentPage;
}

public void setCurrentPage(Integer currentPage) {
this.currentPage = currentPage;
}

public Integer getPageSize() {
return pageSize;
}

public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}

public String getOrderByName() {
return orderByName;
}

public void setOrderByName(String orderByName) {
this.orderByName = orderByName;
}

public String getOrderBuType() {
return orderBuType;
}

public void setOrderBuType(String orderBuType) {
this.orderBuType = orderBuType;
}
//提供查询里面用的当前页面方法
public Integer getJpaPage(){
return currentPage-1;
}
//排序方法 有字段才能排序 佛则不排序
public Sort createSort(){
Sort sort=null;
//判断字段是否有值
if(orderByName!=null){
Sort.Direction type="ASC".equals(orderBuType.toUpperCase())?Sort.Direction.ASC:Sort.Direction.DESC;
sort=new Sort(type,orderByName);
}
return sort;
}
public abstract Specification createSpecification();
}
继承抽象类自己的方法
package cn.itsource.aisell.query;

import cn.itsource.aisell.domain.Employee;
import com.github.wenhao.jpa.Specifications;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;

public class EmployeeQuery extends BaseQuery {
private String username;
private String email;
private Integer age;

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

@Override
public Specification createSpecification() {
Specification<Employee> spe = Specifications.<Employee>and().
like(StringUtils.isNotBlank(username),
"username", "%" + username + "%")
.gt(age != null, "age", age)
.build();

return spe;
}
}

测试

package cn.itsource.aisell;

import cn.itsource.aisell.domain.Employee;
import cn.itsource.aisell.query.EmployeeQuery;
import cn.itsource.aisell.repository.EmployeeRepository1;
import com.github.wenhao.jpa.Specifications;
import org.apache.commons.lang3.StringUtils;
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;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestJpaSpec{
/* @Autowired
private EmployeeRepository1 employeeRepository1;

@Test
public void testSpec1() throws Exception{

EmployeeQuery employeeQuery = new EmployeeQuery();
employeeQuery.setUsername("1");
employeeQuery.setAge(18);
Specification<Employee> spe = Specifications.<Employee>and().
like(StringUtils.isNotBlank(employeeQuery.getUsername()),
"username", "%" + employeeQuery.getUsername() + "%")
.gt(employeeQuery.getAge() != null, "age", employeeQuery.getAge())
.build();
//排序
Sort sort = null;
if(employeeQuery.getOrderByName()!= null){
String orderByName = employeeQuery.getOrderByName();
Sort.Direction direction = null;
if(employeeQuery.getOrderBuType().equals("DESC")){
direction = Sort.Direction.DESC;
}else{
direction = Sort.Direction.ASC;
}
//组装Sort
sort =new Sort(direction,orderByName);
}
//分页
Pageable pageable = new PageRequest(employeeQuery.getJpaPage(), employeeQuery.getPageSize(), sort);


Page<Employee> employees = employeeRepository1.findAll(spe, pageable);
for (Employee employee : employees) {
System.out.println(employee);
}
}
*/
@Autowired
private EmployeeRepository1 employeeRepository1;
@Test
public void testSpec2() throws Exception{
EmployeeQuery employeeQuery = new EmployeeQuery();
employeeQuery.setUsername("a");
employeeQuery.setAge(18);


Specification spec = employeeQuery.createSpecification();
System.out.println("0000111"+spec);
Sort sort = employeeQuery.createSort();
System.out.println("employeeQuery.getJpaPage()"+employeeQuery.getJpaPage()+"employeeQuery.getPageSize()"+employeeQuery.getPageSize());
Pageable pageable = new PageRequest(employeeQuery.getJpaPage(), employeeQuery.getPageSize(), sort);
System.out.println("0000"+pageable);
Page<Employee> lists = employeeRepository1.findAll(spec, pageable);
for (Employee employee : lists) {
System.out.println(employee);
}
}
}


没啥总结的。自己看代码
 
 
posted @ 2019-08-02 23:07  入门小郑  阅读(240)  评论(0编辑  收藏  举报