Spring Data JPA 查询

1.命名查询 在StudentRepository接口中 定义命名查询,不需要实现类 参考使用 Spring Data JPA 简化 JPA 开发  

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
 
@Repository
public interface StudentRepository extends JpaRepository,JpaSpecificationExecutor {

	Student findByName(String name);

}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class StudentServiceImpl implements StudentService {

	@Autowired
	private StudentRepository studentRepository;
 
	@Override
	public Student findByName(String name) {
		Student student = studentRepository.findByName(name); //使用命名查询
		System.out.println("==============student===" + student.toString());
		return null;
	}

}

2.分页查询  pageNumber是从0开始, pageNumber=0,pageSize=3 就是获取前3条 参考创建分页Pageable变量

创建Pageable对象,再查询

import java.util.List;

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.stereotype.Service;

@Service
public class StudentServiceImpl implements StudentService {

	@Autowired
	private StudentRepository studentRepository;
 
	// 分页获取
	@Override
	public List findAllPageable(Integer pageNumber, Integer pageSize) {

		Pageable pageable = new PageRequest(pageNumber, pageSize); // 创建分页对象
		Page students = studentRepository.findAll(pageable);
		Long total = students.getTotalElements(); // 符合条件的总记录条数
		List studentsList = students.getContent();// 这一页的所有记录 
		return null;
	}

 
}

3.先排序 再分页 查询 : 创建Sort对象,再用Sort对象创建 Pageable对象,再查询 参考Spring Data JPA 多属性排序

根据一个字段排序   

Sort sort = new Sort(Direction.DESC, "homeTel");// 排序方式  根据homeTel降序排列	

 多属性排序 根据多个字段排序,排序方式一样 

Sort sort = new Sort(Sort.Direction.DESC, "homeTel", "name");//  根据homeTel和name降序排列	

  多属性排序  根据多个字段排序,排序方式不一样

//先根据homeTel降序排列,再根据name的升序排列
Sort sort = new Sort(Direction.DESC, "homeTel").and(new Sort(Direction.ASC, "name"));
@Service
public class StudentServiceImpl implements StudentService {

	@Autowired
	private StudentRepository studentRepository;	  

	//根据条件排序 再分页获取
	@Override
	public List findAllPageableBySort(Integer pageNumber, Integer pageSize) {
		
		Sort sort = new Sort(Direction.DESC, "homeTel");// 排序方式  根据homeTel降序排列		
		Pageable pageable = new PageRequest(pageNumber, pageSize, sort);// 分页对象		
		Page students = studentRepository.findAll(pageable);// 查询

		Long total = students.getTotalElements(); // 符合条件的总记录条数
		List studentsList = students.getContent();// 这一页的所有记录

		return null;
	}

	//根据多个条件先排序 再分页获取
	@Override
	public List findAllPageableByMultiSort(Integer pageNumber, Integer pageSize) {

		// 根据多个条件排序   先根据homeTel降序排列,再根据name的升序排列
		Sort sort = new Sort(Direction.DESC, "homeTel").and(new Sort(Direction.ASC, "name"));		
		Pageable pageable = new PageRequest(pageNumber, pageSize, sort);// 分页对象		
		Page students = studentRepository.findAll(pageable);// 查询

		Long total = students.getTotalElements(); // 符合条件的总记录条数
		List studentsList = students.getContent();// 这一页的所有记录

		return null;
	}

}

4.条件化查询  用查询条件创建Specification对象 参考Spring Data JPA Specification查询

使用Criteria查询 Criteria查询是面向对象查询, root就是一个对象,root.get("name")就是name属性可以级联获取属性

每一个查询条件创建一个Specification对象,如果有多个查询条件,就把多个Specification对象and或or成最后一个总的Specification对象。

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.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.jpa.domain.Specification;
import org.springframework.stereotype.Service;

@Service
public class StudentServiceImpl1 implements StudentService {

	@Autowired
	private StudentRepository studentRepository;

	/*一个查询条件*/
	@Override
	public List findPageableByParam(Integer pageNumber, Integer pageSize, String name) {

		// 1.创建Pageable对象
		Pageable pageable = new PageRequest(pageNumber, pageSize);
		// 2.根据查询条件 创建Specification对象
		Specification specification = new Specification() {
			@Override
			public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery,
					CriteriaBuilder criteriaBuilder) {
				Predicate predicate = criteriaBuilder.equal(root.get("name").as(String.class), name);
				return predicate;
			}
		};
		// 3.查询
		Page students = studentRepository.findAll(specification, pageable);

		Long total = students.getTotalElements(); // 符合条件的总记录条数
		List studentsList = students.getContent();// 这一页的所有记录

		return studentsList;
	}
 
	/*多个查询条件*/
	@Override
	public List findPageableByParams(Integer pageNumber, Integer pageSize, String name, Long homeTel) {
		// 1.创建Pageable对象
		Pageable pageable = new PageRequest(pageNumber, pageSize);
		// 2.根据查询条件 创建Specification对象
		Specification specification = new Specification() {
			@Override
			public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery,
					CriteriaBuilder criteriaBuilder) {
				// name条件
				Predicate namePredicate = criteriaBuilder.like(root.get("name").as(String.class), "%" + name + "%");
				// homeTel条件
				Predicate predicate = criteriaBuilder.equal(root.get("homeTel").as(Long.class), homeTel);
				// and 两个条件
				Predicate and = criteriaBuilder.and(namePredicate, predicate);
				return and;
			}
		};
		// 3.查询
		Page students = studentRepository.findAll(specification, pageable);

		Long total = students.getTotalElements(); // 符合条件的总记录条数
		List studentsList = students.getContent();// 这一页的所有记录
	
		return studentsList;
	}

}

5.Spring Data JPA 原生sql查询 参考 Spring Data JPA @Query

在Repository层 用@Query注解做查询  @Query 默认是按对象查询,nativeQuery = true:按sql原生语句查询

增删改操作 需用要@Modifying注解和@Transactional注解,并且返回值只能是int或者Integer

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

@Repository
public interface StudentRepository extends JpaRepository, JpaSpecificationExecutor {


	@Query(value = "SELECT * from t_student where id= :id and name like CONCAT('%',:name,'%') ", nativeQuery = true)
	List findOneStudent1(@Param("id") Long id, @Param("name") String name);

}

Spring Data JPA提供的查询 很多时候不能满足业务需求,这时候就需要使用原生sql实现查询

 

5.1.需要按汉语拼音排序

基于oracle数据库,在oracle数据库,把查询结果按汉语拼音排序 

select * from TB_STUDENT  where class_no = '' order by NLSSORT(student_name,'NLS_SORT=SCHINESE_PINYIN_M')

Spring Data JPA原生sql查询

import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;


public interface UserRepository extends JpaRepository, JpaSpecificationExecutor {


	@Query(value = "select * from TB_STUDENT  where class_no = :classNo order by NLSSORT(student_name,'NLS_SORT=SCHINESE_PINYIN_M')", nativeQuery = true)
	List findAllByClass(@Param("classNo") String classNo);


}

5.2 只查询部分字段


import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;


@Repository
public interface MatrixReportRepository
		extends JpaRepository, JpaSpecificationExecutor {

	@Query(value = "select username,age from TB_STUDENT Where class_no= :classNo ", nativeQuery = true)
	List findSubStudents(@Param("classNo") String classNo);
	
	 

}

5.3 distinct 或者 group by

你可能感兴趣的:(#,Spring,Data,JPA)