005_Spring Data JPA条件查询

1. 创建一个名为spring-data-jpa-specification-executor的Java项目, 同时添加相关jar包, 并添加JUnit能力。

005_Spring Data JPA条件查询_第1张图片

2. 查看JpaSpecificationExecutor接口下的方法 

005_Spring Data JPA条件查询_第2张图片

3. 新建User.java 

package com.bjbs.pojo;

import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.format.annotation.DateTimeFormat;

@Entity // 指定该类是实体类
@Table(name = "user") // 指定数据库表名(表名和实体类对应)
public class User implements Serializable {
	private static final long serialVersionUID = 1L;

	@Id // 指定为主键
	@GeneratedValue(strategy = GenerationType.IDENTITY) // 指定主键生成策略
	@Column(name = "id") // 指定表中列名(列名和属性名对应)
	private Integer id;

	@Column(name = "name")
	private String name;

	@Column(name = "sex")
	private String sex;
	
	@Column(name = "birthday")
	@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
	private Date birthday;

	@Column(name = "address")
	private String address;

	public User() {
	}

	public User(String name, String sex, Date birthday, String address) {
		this.name = name;
		this.sex = sex;
		this.birthday = birthday;
		this.address = address;
	}

	public User(Integer id, String name, String sex, Date birthday, String address) {
		this.id = id;
		this.name = name;
		this.sex = sex;
		this.birthday = birthday;
		this.address = address;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", sex=" + sex + ", birthday=" + birthday + ", address=" + address
				+ "]";
	}
}

4. 新建UserRepository.java, 实现Repository和JpaSpecificationExecutor接口。

package com.bjbs.dao;

import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.Repository;
import com.bjbs.pojo.User;

/**
 * 参数一T: 当前需要映射的实体; 参数二 T: 当前映射的实体中的id的类型
 */
public interface UserRepository extends Repository, JpaSpecificationExecutor {

}

5. 新建UserService.java

package com.bjbs.service;

import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import com.bjbs.pojo.User;

public interface UserService {
	public User findOne(Specification spec);

	public List findAll(Specification spec);

	public Page findAll(Specification spec, Pageable pageable);

	public List findAll(Specification spec, Sort sort);
}

6. 新建UserServiceImpl.java

package com.bjbs.service.impl;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.bjbs.dao.UserRepository;
import com.bjbs.pojo.User;
import com.bjbs.service.UserService;

@Service
@Transactional
public class UserServiceImpl implements UserService {
	@Autowired
	private UserRepository userRepository;

	@Override
	public User findOne(Specification spec) {
		return userRepository.findOne(spec);
	}

	@Override
	public List findAll(Specification spec) {
		return userRepository.findAll(spec);
	}

	@Override
	public Page findAll(Specification spec, Pageable pageable) {
		return userRepository.findAll(spec, pageable);
	}

	@Override
	public List findAll(Specification spec, Sort sort) {
		return userRepository.findAll(spec, sort);
	}
	
}

7. 新建TestUserRepository.java

package com.bjbs.test;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
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.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.bjbs.pojo.User;
import com.bjbs.service.UserService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestUserRepository {
	@Autowired
	private UserService userService;
	
	/**
	 * 查询名字叫'曹操'的用户
	 */
	@Test
	public void findOne() {
		Specification spe = new Specification() {
			/**
			 * @return Predicate: 定义了查询条件。
			 * @param Root root: 根对象, 封装了查询条件的对象。
			 * @param CriteriaQuery query: 定义了一个基本的查询, 一般不使用。
			 * @param CriteriaBuilder cb: 创建一个查询条件。
			 */
			@Override
			public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
				Predicate pre = cb.equal(root.get("name"), "曹操");
				return pre;
			}
		};
		
		User userDb = userService.findOne(spe);
		System.out.println(userDb);
	}
	
	/**
	 * 查询名字叫'曹操'和性别为'男'的用户
	 */
	@Test
	public void findOneByNameAndSex() {
		Specification spe = new Specification() {
			@Override
			public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
				List list = new ArrayList();
				list.add(cb.equal(root.get("name"), "曹操"));
				list.add(cb.equal(root.get("sex"), "男"));
				Predicate[] arr = new Predicate[list.size()];
				return cb.and(list.toArray(arr));
			}
		};
		
		User userDb = userService.findOne(spe);
		System.out.println(userDb);
	}
	
	/**
	 * 查询名字叫'曹操'和住址为'安徽省亳州市'的用户
	 */
	@Test
	public void findOneByNameAndAddress() {
		Specification spe = new Specification() {
			@Override
			public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
				return cb.and(cb.equal(root.get("name"), "曹操"), cb.equal(root.get("address"), "安徽省亳州市"));
			}
		};
		
		User userDb = userService.findOne(spe);
		System.out.println(userDb);
	}
	
	/**
	 * 查询名字叫'曹操'或'曹植'的用户
	 */
	@Test
	public void findByNameOr() {
		Specification spe = new Specification() {
			@Override
			public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
				return cb.or(cb.equal(root.get("name"), "曹操"), cb.equal(root.get("name"), "曹植"));
			}
		};
		
		List list = userService.findAll(spe);
		for (User user : list) {
			System.out.println(user);
		}
	}
	
	/**
	 * 查询姓李的用户
	 */
	@Test
	public void findByNameLike() {
		Specification spe = new Specification() {
			@Override
			public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
				return cb.like(root.get("name"), "李%");
			}
		};
		
		List list = userService.findAll(spe);
		for (User user : list) {
			System.out.println(user);
		}
	}
	
	/**
	 * 分页查询id在47和51之间的用户
	 */
	@Test
	public void pageable() {
		Specification spe = new Specification() {
			@Override
			public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
				return cb.between(root.get("id"), 47, 51);
			}
		};
		
		Pageable pageable = new PageRequest(0, 5);
		Page list = userService.findAll(spe, pageable);
		for (User user : list) {
			System.out.println(user);
		}
	}
	
	/**
	 * 排序查询id>51
	 */
	@Test
	public void sort() {
		Specification spe = new Specification() {
			@Override
			public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
				return cb.greaterThan(root.get("id"), 51);
			}
		};
		
		Sort sort = new Sort(Direction.DESC, "id");
		List list = userService.findAll(spe, sort);
		for (User user : list) {
			System.out.println(user);
		}
	}
	
	/**
	 * 分页排序查询id>=51
	 */
	@Test
	public void pageableAndSort() {
		Specification spe = new Specification() {
			@Override
			public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
				return cb.ge(root.get("id"), 51);
			}
		};
		
		Sort sort = new Sort(Direction.DESC, "id");
		Pageable pageable = new PageRequest(0, 3, sort);
		Page list = userService.findAll(spe, pageable);
		for (User user : list) {
			System.out.println(user);
		}
	}
}

8. 在src下新建application.properties

spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://192.168.25.138:3306/StudyMybatis?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=lyw123456

9. 在src下新建applicationContext.xml



	
	
	

	
	
		
		
		
		
	

	
	
		
		
			
				
				
				
				
				
				
				
			
		
		
		
			
				com.bjbs.pojo
			
		
	

	
	
		
	

	
	

	
	

	
	
	

10. 数据库user表

005_Spring Data JPA条件查询_第3张图片

11. 查询名字叫'曹操'的用户 

005_Spring Data JPA条件查询_第4张图片

12. 查询名字叫'曹操'和性别为'男'的用户 

005_Spring Data JPA条件查询_第5张图片

13. 查询名字叫'曹操'和住址为'安徽省亳州市'的用户 

005_Spring Data JPA条件查询_第6张图片

14. 查询名字叫'曹操'或'曹植'的用户 

005_Spring Data JPA条件查询_第7张图片

15. 查询姓'李'的用户 

005_Spring Data JPA条件查询_第8张图片

16. 分页查询id在47和51之间的用户 

005_Spring Data JPA条件查询_第9张图片

17. 排序查询id>51 

005_Spring Data JPA条件查询_第10张图片

18. 分页排序查询id>=51 

005_Spring Data JPA条件查询_第11张图片

你可能感兴趣的:(SpringData,spring,java,intellij-idea)