一. 自定义@Query查询:用于查询复杂数据哦!
package com.hlx.dao;
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 com.hlx.entity.Student;
/**
* 数据底层 只要继承这个类就OK!
*
* @author Administrator
*
* JpaRepository<Student实体类, Integer主键数据类型>
*
*/
public interface StudentDao extends JpaRepository<Student, Integer>,JpaSpecificationExecutor<Student> {
/**
*(1) 自定义@Query查询:用于复杂数据哦!
*
* 使用HQL语句:Student:必须是实体类类名哦!
*
* @param name
* ?1:代表第一个参数name
* @return
*/
@Query("select st from Student st where st.name like %?1%")
public List<Student> findByName(String name);
/**
*
* 推荐使用本地sql哦!
* 使用SQL语句 随机查询几条数据
*
* @param number
* @return
*
* nativeQuery=true 开启本地查询
*/
@Query(value = "select * from t_student order by RAND() limit ?1",nativeQuery=true)
public List<Student> listRandom(Integer number);
//动态查询Specfaction的使用:用于多条件查询时;还要实现另一个接口哦JpaSpecificationExecutor<Student> !
}
(a)使用HQL语句
(b)推荐使用本地SQL语句
@Controller
@RequestMapping("/student")
public class StudentController {
@Resource // 注入dao
private StudentDao studentDao;
@ResponseBody // 返回josn
@GetMapping("/findName")
public List<Student> findName() {
return studentDao.findByName("q"); // 调用模糊查询的方法
}
@ResponseBody // 返回josn
@GetMapping("/listRandom")
public List<Student> listRandom() {
return studentDao.listRandom(2); // 调用查询的方法
}
}
浏览页面
根据q模糊查询
随机产生2个
再重新加载又不同了!
二.动态查询Specification的使用:用于多条件查询时;还要继承另一个接口JpaSpecificationExecutor<T>
/**
* 根据条件查询数据
*
* @return
*/
@RequestMapping("/list2")
public ModelAndView listCondition(Student stu) {
// 试图对象
ModelAndView view = new ModelAndView("all");
// 调用方法==>使用specification
List<Student> list = studentDao.findAll(new Specification<Student>() {
// CriteriaBuilder构造; Root<Student>获得字段名
@Override
public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> arg1, CriteriaBuilder cb) {
// 构造这个对象
Predicate predicate = cb.conjunction();
// 判断
if (stu != null) {
if (stu.getName() != null &&! "".equals(stu.getName())) {
// 添加name模糊查询
predicate.getExpressions().add(cb.like(root.get("name"), "%" + stu.getName() + "%"));
}
if (stu.getPass() != null &&! "".equals(stu.getPass())) {
// 添加pass模糊查询
predicate.getExpressions().add(cb.like(root.get("pass"), "%" + stu.getPass() + "%"));
}
}
return predicate;
}
});
// 保存数据,调用查询所有的方法
view.addObject("students", list);
return view;
}
all.ftl页面
浏览页面
根据username=i查询
两个同时查询
全为空,则查询所有的数据
根据password=1查看