1.1先把maven项目建好
导入所有包 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>
注:如果配置完后没有自动导包,办法如下:
Settings > Maven > Importing > Import maven project automatically
1.2 .配置applicationContext.xml文件
<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="cn.itsource.pss.service" />
<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="cn.itsource.aisell.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="cn.itsource.pss.repository" transaction-manager-ref="transactionManager"
entity-manager-factory-ref="entityManagerFactory" />
beans>
1.3.准备Domain
//父类:BaseDomain
package cn.itsource.pss.domain;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.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 cn.itsource.pss.repository;
import cn.itsource.pss.domain.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* 必需继续JpaRepository<1v,2v>
* 1v:代表你要操作的是哪一个domain对象
* 2v:这个domain对象的主键的类型
* 这个类相当于之前的 dao层 ,而且不需要实现类,因为jpa会自动给你创建
*/
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}
1.5 测试集成是否成功
package cn.itsource.repository;
import cn.itsource.pss.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.1.普通的CRUD
//获取所有数据
@Test
public void testFindAll() throws Exception{
List<Employee> emps = employeeRepository.findAll();
for (Employee emp :emps){
System.out.println(emp);
}
}
//根据id到一条数据
@Test
public void testFindOne() throws Exception{
Employee employee = employeeRepository.findOne(1L);
System.out.println(employee);
}
//添加与修改都使用save(主要看对象有没有id)
@Test
public void testSave() throws Exception{
Employee employee = new Employee();
//employee.setId(103L);
employee.setUsername("张三");
employee.setPassword("1234");
employee.setEmail("[email protected]");
employeeRepository.save(employee);
}
//删除数据
@Test
public void testDelete() throws Exception{
employeeRepository.delete(103L);
}
//得到总条数
@Test
public void testCount(){
System.out.println(employeeRepository.count());
}
2.2.分页排序功能
//进行分页功能
@Test
public void testPage() {
//1.需要先创建一个page对象(注意:页数是从0开始计算【0就是第1页】)
Pageable pageable = new PageRequest(0, 10);
//2.进行查询
Page<Employee> page = employeeRepository.findAll(pageable);
System.out.println(page.getTotalElements()); //总条数
System.out.println(page.getTotalPages()); //总页数
System.out.println(page.getContent()); //当前页数据
System.out.println(page.getNumber()); //第几页
System.out.println(page.getNumberOfElements()); //当前页有多少个数据
System.out.println(page.getSize()); //每页条数
}
//进行排序功能
@Test
public void testSort() {
//排序 :第一个参数是排序的规则(DESC/ASC) 后面参数是排序的字符
Sort sort = new Sort(Sort.Direction.DESC,"username");
List<Employee> emps = employeeRepository.findAll(sort);
for (Employee emp : emps) {
System.out.println(emp);
}
}
//分页与排序的集成
@Test
public void testPageAndSort() {
//排序 :第一个参数是排序的规则(DESC/ASC) 后面参数是排序的字符
Sort sort = new Sort(Sort.Direction.DESC,"username");
Pageable pageable = new PageRequest(0, 10,sort);
//2.进行查询
Page<Employee> page = employeeRepository.findAll(pageable);
for (Employee employee : page) {
System.out.println(employee);
}
}
2.3 根据条件进行查询
EmployeeRepository 类设置
public interface EmployeeRepository extends JpaRepository<Employee,Long> {
/**
* 单表查询OK --比较方便 -- 掌握
* 多表查询 -- @Query注解查询
*
*/
//想通过员工的名称来查询员工 -- 如果按照一定的规范来写 底层就会解析完成
List<Employee> findEmployeeByUsername(String username);
//LIKE查询
List<Employee> findEmployeeByUsernameLike(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();
}
测试类:
public class TestQuery extends BaseTest{
@Autowired
private EmployeeRepository employeeRepository;
//按照规范查询
@Test
public void testQuery() throws Exception{
List<Employee> employees = employeeRepository.findEmployeeByUsername("bbbb");
for (Employee employee : employees) {
System.out.println(employee);
}
}
//按照规范查询
@Test
public void testQuery1() throws Exception{
List<Employee> employees = employeeRepository.findEmployeeByUsernameLike("%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);
}
}
@Test
public void testQuery4() throws Exception{
List<Employee> emps= employeeRepository.query03("b","%2%");
for (Employee emp : emps) {
System.out.println(emp);
}
}
@Test
public void testQuery5() throws Exception{
System.out.println(employeeRepository.query04());
}
}
JpaSpecificationExecutor(JPA规则执行者)是JPA2.0提供的Criteria API的使用封装,可以用于动态生成Query来满足我们业务中的各种复杂场景。
Spring Data JPA为我们提供了JpaSpecificationExecutor接口,只要简单实现toPredicate方法就可以实现复杂的查询。
// 我们要使用这个接口中的方法,首先让我们的接口也去继承这个接口,其他就不用了
public interface EmployeeRepository extends JpaRepository,JpaSpecificationExecutor {}
单个条件的查询
@Test
public void testFind() {
//
List<Employee> emps = employeeRepository.findAll(
new Specification<Employee>() {
@Override
public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
Path path = root.get("username");//拿到要做查询的字段
Predicate p = cb.like(path, "%1%");//like代表做模糊查询,后面就是它的条件值
return p;
}
}
);
for (Employee emp : emps) {
System.out.println(emp);
}
}
```java
多个条件查询
@Test
public void testFind02() {
Specification spec = new Specification<Employee>() {
@Override
public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
//加上第一个条件: username like '%1%'
Path path1 = root.get("username");
Predicate p1 = cb.like(path1, "%1%");
//加上第二个条件: email like '%2%'
Path path2 = root.get("email");
Predicate p2 = cb.like(path2,"%2%");
//加上第二个条件: age < 20
Path path3 = root.get("age");
Predicate p3 = cb.lt(path3, 20);
//下面是加上or的条件的方案
//Predicate p3 = cb.or(p1,p2);
//把两个查询条件放到query对象中去(条件使用where)
CriteriaQuery where = query.where(p1, p2, p3);
//返回查询条件
return where.getRestriction();
}
};
List<Employee> emps = employeeRepository.findAll(spec);
for (Employee emp : emps) {
System.out.println(emp);
}
}
条件查询+分页排序
@Test
public void testFind03() {
Specification spec = new Specification<Employee>() {
@Override
public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
//加上条件: username like '%1%'
Path path1 = root.get("username");
Predicate p1 = cb.and(cb.like(path1, "%1%"));
//把两个查询条件放到query对象中去(条件使用where)
CriteriaQuery where = query.where(p1);
//返回查询条件
return where.getRestriction();
}
};
//排序 :第一个参数是排序的规则(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);
}
}
这是一个对于咱们刚才的动态生成Query功能的一个封装版,如果我们使用这个插件,在完成查询与分页的时候功能会简单不少。
在Maven中引入相应的包
pom.xml(): 刚才已经加进去了
<dependency>
<groupId>com.github.wenhaogroupId>
<artifactId>jpa-specartifactId>
<version>3.1.1version>
<exclusions>
<exclusion>
<groupId>*groupId>
<artifactId>*artifactId>
exclusion>
exclusions>
dependency>
单个条件查询
@Test
public void testSpecFind01() {
Specification<Employee> spec = Specifications.<Employee>and().like("username", "%1%").build();
List<Employee> emps = employeeRepository.findAll(spec);
for (Employee emp : emps) {
System.out.println(emp);
}
}
多个条件查询
@Test
public void testSpecFind02() {
Specification<Employee> spec = Specifications.<Employee>and().like("username", "%1%")
.like("email","%2%").lt("age", 20).build();
List<Employee> emps = employeeRepository.findAll(spec);
for (Employee emp : emps) {
System.out.println(emp);
}
}
条件+排序分页功能
/条件集成+分页
@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);
}
}