本文章学习根据:https://www.hiai.top/archives/321.html 中配置继续学习

一. 自定义查询@Query

1.1. 自定义模糊查询

模糊查询:121

2020-03-05_182806.jpg

代码实现:


/**
 * public class StudentController 中的代码
 * Jpa中自定义查询Query学习
 * 1.Spring Boot模糊查询第一种方法,返回JSON数据
 * @return
 */
@ResponseBody
@GetMapping("/queryName")
public List<Student> queryByName(){
    return studentRepository.findByName("121");
}
 
 
/**
 * public interface StudentRepository 中的代码
 * 模糊查询数据
 * 常用错误,(XXX) is not mapped 问题
 * 解决方法,下面的Student 不是数据库表名字,而是实体名
 * @param username
 * @return
 */
@Query(" select b from Student b where b.username like %?1% ")
public List<Student> findByName(String username);

1.2. 自定义随机本地查询几条数据

随机查询3条数据:

2020-03-05_173402.jpg

代码实现:

/**
 * public class StudentController 中的代码
 * Jpa中自定义查询Query学习
 * 2.Spring Boot随机查询几条数据,返回JSON数据
 * @return
 */
@ResponseBody
@GetMapping("/randomList")
public List<Student> randomByName(){
    return studentRepository.randomList(3);
}
 
 
/**
 * public interface StudentRepository 中的代码
 * 本地随机查询几条数据,nativeQuery默认是false,这里进行开启
 * @param n
 * @return
 */
@Query(value="select * from t_student order by RAND() limit ?1",nativeQuery=true)
public List<Student> randomList(Integer n);

二. 动态查询Specification使用

封装Specification查询条件,在Spring Data JPA 2.0以前使用 Specifications 这个辅助类来操作where、not、and和or连接,在2.0版本以后这个类会被剔除,可以直接使用 Specification 自身对象来操作where多条件连接

2.1. 效果预览

1583403646599.gif

2.2. 代码实现

JAVA代码:

/**
 * public class StudentController 中的代码
 * Specification动态查询,
 * 比如用户需要两个条件进行查询,这时就需要动态判断,就是拼接SQL
 * @param student
 * @return
 */
@RequestMapping("/list2")
public ModelAndView ListTwo(Student student){
    ModelAndView mav = new ModelAndView();
    /**
     * 使用匿名内部类,通过构造使用条件拼接
     * 后期要写在Service中,以及排序逻辑有利于代码开发
     * Root:查询哪个表
     * CriteriaQuery:查询哪些字段,排序是什么
     * CriteriaBuilder:字段之间是什么关系,如何生成一个查询条件,每一个查询条件都是什么方式
     */
    List<Student> studentList = studentRepository.findAll(new Specification<Student>() {
        @Override
        public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> query, CriteriaBuilder cd) {
 
            //动态拼接
            Predicate predicate = cd.conjunction();
            if(student != null){
                //判断第一个条件
                if(student.getUsername() != null && !"".equals(student.getUsername())){
                    //获取表达式
                    predicate.getExpressions().add(cd.like(root.get("username"), "%"+student.getUsername()+"%"));
                }
                //判断第二个条件
                if(student.getSex() != null && !"".equals(student.getSex())){
                    //获取表达式
                    predicate.getExpressions().add(cd.like(root.get("sex"), "%"+student.getSex()+"%"));
                }
            }
            return predicate;
        }
    });
    
    //返回页面
    mav.addObject("studentList",studentList);
    mav.addObject("title","动态查询");
    mav.setViewName("studentList2");
    return mav;
}

HTML代码:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"></meta>
<title th:text="${title}+'-拾光博客'"></title>
</head>
<body>
    <p><a href="/student/addview">添加学生</a></p>
    <form method="post" action="/student/list2">
        学生姓名:<input type="text" name="username"/>&nbsp;&nbsp;&nbsp;&nbsp;
        学生性别:<input type="text" name="sex"/>&nbsp;&nbsp;&nbsp;&nbsp;
        <input type="submit" value="搜索"/>
    </form>
    
    <table>
        <tr>
            <th>编号</th>
            <th>姓名</th>
            <th>性别</th>
            <th>年龄</th>
            <th>操作</th>
        </tr>
        <tr th:each="student:${studentList}">
            <td th:text="${student.id}"></td>
            <td th:text="${student.username}"></td>
            <td th:text="${student.sex}"></td>
            <td th:text="${student.age}"></td>
            <td>
                <!-- <a href="/student/studel/?id=" th:value="${student.id}">删除</a> -->
                <a th:href="@{'/student/stuedit/'+${student.id}}">修改</a>
                <a th:href="@{'/student/studel/'+${student.id}}">删除</a>
            </td>
        </tr>
    </table>
</body>
</html>