my aisell
一.什么是SpringDataJpa?
1.1概念
- 它是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>com.yangrui</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>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<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>
<!-- Spring要集成邮件,定时器,模板技术等等 -->
<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>
<!--hibernate对于jpa的支持包-->
<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>
<!-- 对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>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
三.集成SpringDataJpa
3.1jdbc.xml配置
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///pss
jdbc.username=root
jdbc.password=123456
3.2applicationContext-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
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
">
<!--扫描dao层-->
<context:component-scan base-package="com.yangrui.aisell.repository" />
<!--扫描service层-->
<context:component-scan base-package="com.yangrui.aisell.service" />
<!--引入jdbc.properties-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--DataSource配置,记得要关闭-->
<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>
<!--entityManagerFactory配置-->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--扫描包(jpa在扫描)-->
<property name="packagesToScan" value="com.yangrui.aisell.domain"/>
<!--适配器,告诉Spring是用的哪一个实现 Hibernate-->
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<!--generateDdl:相当于update-->
<property name="generateDdl" value="false"/>
<!--方言-->
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/>
<!--显示sql-->
<property name="showSql" value="true"/>
</bean>
</property>
</bean>
<!--创建jpa事务-->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!--支持事务注解-->
<tx:annotation-driven/>
<!--
扫描dao层,只要发现它扫描到的接口继承了 Repository
就会自动完成相应功能(实现类就有了)
-->
<jpa:repositories base-package="com.yangrui.aisell.repository"
entity-manager-factory-ref="entityManagerFactory"
transaction-manager-ref="transactionManager"/>
</beans>
3.3domain准备
3.3.1BaseDomain(父类)
@MappedSuperclass
public class BaseDomain {
@Id
@GeneratedValue
protected Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
3.3.2Employee
@Entity
@Table(name = "employee")
public class Employee extends BaseDomain {
private String username;
private String password;
private String email;
private Integer age;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
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 String toString() {
return "Employee{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
", email='" + email + '\'' +
", age=" + age +
", id=" + id +
'}';
}
}
3.4dao层准备
3.4.1repository接口
JpaRepository:自动实现了crud功能语句
JpaSpecificationExecutor:规范,也就是进行了封装,使代码以面向对象的形式
public interface EmployeeRepositroy extends JpaRepository<Employee,Long>,JpaSpecificationExecutor<Employee> {
//用户名查询
Employee findByUsername(String username);
//用户名模糊查询
List<Employee> findByUsernameLike(String username);
//用户名和邮件模糊查询
List<Employee> findByUsernameLikeAndEmailLike(String username,String email);
//jpql
@Query("select o from Employee o where o.username=?1")
Employee queryUsername(String username);
@Query("select o from Employee o where o.username like ?1")
List<Employee> queryUsernameLike(String username);
@Query("select o from Employee o where o.username like :username and o.email like :email")
List<Employee> queryUsernameAndEmailLike(@Param("username") String username, @Param("email")String email);
//原生SQL
@Query(nativeQuery = true,value = "select * from employee")
List<Employee> queryEmployee();
}
四. CRUD功能测试
4.1基本CRUD
RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class EmployeeRepositoryTest {
@Autowired
private EmployeeRepositroy employeeRepositroy;
@Test
public void testFindAll() throws Exception{
List<Employee> list = employeeRepositroy.findAll();
list.forEach(e-> System.out.println(e));
}
@Test
public void testFindOne() throws Exception{
Employee employee = employeeRepositroy.findOne(6L);
System.out.println(employee);
}
/*
* 添加和修改是save()方法
* 没有id,添加
* 有id,修改
* */
@Test
public void testSaveAdd() throws Exception{
Employee employee = new Employee();
employee.setUsername("蔷薇");
employee.setPassword("123456");
employeeRepositroy.save(employee);
}
@Test
public void testSaveUpdate() throws Exception{
Employee employee = new Employee();
employee.setId(274L);
employee.setUsername("蔷薇");
employee.setPassword("123");
employeeRepositroy.save(employee);
}
@Test
public void testDelete() throws Exception{
employeeRepositroy.delete(274L);
}
4.2分页和排序
/*
* 分页查询
* Pageable 接口
* PageRequest实现
* */
@Test
public void testPage() throws Exception{
PageRequest pageRequest = new PageRequest(0,10);
Page<Employee> page = employeeRepositroy.findAll(pageRequest);
page.forEach(e-> System.out.println(e));
//总条数
System.out.println(page.getTotalElements());
//总页数
System.out.println(page.getTotalPages());
//每页数据
List<Employee> content = page.getContent();
System.out.println(content);
}
//排序
@Test
public void testSort() throws Exception{
//第一个参数:排序方式,第二个参数:根据属性排序
Sort sort = new Sort(Sort.Direction.DESC,"id");
List<Employee> list = employeeRepositroy.findAll(sort);
list.forEach(e-> System.out.println(e));
}
//分页排序
@Test
public void testPageSort() throws Exception{
Sort sort = new Sort(Sort.Direction.DESC,"id");
PageRequest pageRequest = new PageRequest(0,10,sort);
Page<Employee> page = employeeRepositroy.findAll(pageRequest);
page.forEach(e-> System.out.println(e));
}
4.3名称规则(条件查询)
//根据用户名查询数据
@Test
public void testfindByUsername() throws Exception{
Employee username = employeeRepositroy.findByUsername("蔷薇");
System.out.println(username);
}
//模糊查询
@Test
public void testfindByUsernameLike() throws Exception{
List<Employee> list = employeeRepositroy.findByUsernameLike("%11%");
list.forEach(e-> System.out.println(e));
}
//用户名,email模糊查询
@Test
public void testfindByUsernameLikeAndEmailLike() throws Exception{
List<Employee> list = employeeRepositroy.findByUsernameLikeAndEmailLike("%11%", "%a%");
list.forEach(e-> System.out.println(e));
}
4.4@query注解查询
//jpql
@Test
public void testQueryUsername() throws Exception{
Employee employee = employeeRepositroy.queryUsername("蔷薇");
System.out.println(employee);
}
@Test
public void testQueryUsernameLike() throws Exception{
List<Employee> list = employeeRepositroy.queryUsernameLike("%1%");
list.forEach(e-> System.out.println(e));
}
@Test
public void testqueryUsernameAndEmailLike() throws Exception{
List<Employee> list = employeeRepositroy.queryUsernameAndEmailLike("%1%", "%2%");
list.forEach(e-> System.out.println(e));
}
//原生Sql查询
@Test
public void testNativeQuery() throws Exception{
List<Employee> list = employeeRepositroy.queryEmployee();
list.forEach(e-> System.out.println(e));
}
五.JpaSpecificationExecutor
- JPA的规范执行者
- JPA2.0提供的Criteria API的使用封装
- 需要repository继承JpaSpecificationExecutor接口
5.1简单查询
/**
* Specification:根据规则进行查询
* 用户名进行模糊查询
*/
@Test
public void testSpecification01() throws Exception{
List<Employee> list = employeeRepositroy.findAll(new Specification<Employee>() {
@Override
public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
/**
* root:根,通过根可以拿到字段
* CriteriaQuery:查询对象(不管,用第三个参数)
* CriteriaBuilder:构建CriteriaQuery的构建器对象,用来进行条件组合
*/
//获取用户名路径,不要泛型
Path usernamePath = root.get("username");
//判断(确定)是什么查询条件
Predicate predicate = cb.like(usernamePath, "%1%");
return predicate;
}
});
list.forEach(e-> System.out.println(e));
}
//根据用户名,邮件,年龄 查询
@Test
public void testSpecification02() throws Exception{
List<Employee> list = employeeRepositroy.findAll(new Specification<Employee>() {
@Override
public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
//获取用户名
Path usernamePath = root.get("username");
//获取邮件
Path emailPath = root.get("email");
//获取年龄
Path agePath = root.get("age");
//获取查询条件
Predicate pusename = cb.like(usernamePath, "%1%");
Predicate pemail = cb.like(emailPath, "%2%");
//gt:>大于
Predicate page = cb.gt(agePath, 20);
//条件结合
Predicate predicate = cb.and(pusename, pemail, page);
return predicate;
}
});
list.forEach(e-> System.out.println(e));
}
5.2查询+分页+排序
//查询+分页
@Test
public void testSpecificationPage() throws Exception{
//分页对象
Pageable pageable = new PageRequest(0,5);
Page<Employee> list = employeeRepositroy.findAll(new Specification<Employee>() {
@Override
public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
//获取用户名
Path usernamePath = root.get("username");
return cb.like(usernamePath, "%1%");
}
},pageable);
list.forEach(e-> System.out.println(e));
}
//查询+分页+排序
@Test
public void testSpecificationPageSort() throws Exception{
//创建排序对象
Sort sort = new Sort(Sort.Direction.DESC, "age");
//创建分页对象
Pageable pageable = new PageRequest(0,5,sort);
Page<Employee> list = employeeRepositroy.findAll(new Specification<Employee>() {
@Override
public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
//获取用户名
Path usernamePath = root.get("username");
return cb.like(usernamePath, "%1%");
}
},pageable);
list.forEach(e-> System.out.println(e));
}
六.Jpa-spec
- 把JpaSpecificationExecutor再封装,变得更加简单
6.1简单查询
//用户名,邮件,年龄 模糊查询
@Test
public void testSpec01() throws Exception{
//Specifications: wenhao的包
Specification<Employee> spec = Specifications.<Employee>and()
.like("username", "%1%")
.like("email", "%2%")
.gt("age", 20)
.build();//构建
List<Employee> list = employeeRepositroy.findAll(spec);
list.forEach(e-> System.out.println(e));
}
6.2查询+分页+排序
//查询+分页+排序
@Test
public void testSpec02() throws Exception{
//创建排序对象
Sort sort = new Sort(Sort.Direction.DESC,"age");
//创建分页对象
Pageable pageable = new PageRequest(0,5,sort);
Specification<Employee> spec = Specifications.<Employee>and()
.like("username", "%1%")
.build();
List<Employee> list = employeeRepositroy.findAll(spec);
list.forEach(e-> System.out.println(e));
}
七.Query查询对象抽取
7.1BaseQuery(父类)
- 不管有没有代码都应该创建一个父类
- 公共的代码抽取出来
- 制定规范
- 扩展性高
抽取spec,排序字段,排序对象
public abstract class BaseQuery {
//当前页
private int currentPage = 1;
//每页条数
private int pageSize = 10;
//排序字段
private String orderName;
//排序类型 true:降序,false:升序
private boolean orderType = false;
//子类实现这个方法,规范
public abstract Specification createSpec();
//排序对象的创建
public Sort createSort(){
//判断是否有排序字段
if(StringUtils.isNotBlank(orderName)){
//如果有排序字段,返回排序对象
Sort sort = new Sort(orderType? Sort.Direction.DESC:Sort.Direction.ASC,orderName);
return sort;
}
return null;
}
//从0开始
public int getJpaPage(){
return currentPage-1;
}
public int getCurrentPage() {
return currentPage;
}
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 boolean isOrderType() {
return orderType;
}
public void setOrderType(boolean orderType) {
this.orderType = orderType;
}
}
7.2Employee
查询需要的字段
public class EmployeeQuery extends BaseQuery{
private String username;
private String email;
private Integer age;
@Override
public Specification createSpec(){
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;
}
}
7.3测试
//查询+分页+排序
@Test
public void testSpec03() throws Exception{
//设置参数,模拟前台
EmployeeQuery query = new EmployeeQuery();
query.setUsername("1");
query.setEmail("2");
query.setAge(20);
query.setOrderName("age");
query.setOrderType(true);
//获取排序对象
Sort sort = query.createSort();
//获取分页对象
Pageable pageable = new PageRequest(query.getJpaPage(),query.getPageSize(),sort);
//获取查询对象
Specification spec = query.createSpec();
Page<Employee> page = employeeRepositroy.findAll(spec, pageable);
page.forEach(e-> System.out.println(e));
}