第9讲 9.3 动态查询specification

1,BookDao 添加继承,JapSpecificationExecutor<Book>,

    ps:本例中两个接口可以忽略

package com.cruise.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.cruise.entity.Book;

public interface BookDao extends JpaRepository<Book, Integer>,JpaSpecificationExecutor<Book>{

    @Query("select b from Book b where b.name like  %?1%")
    public List<Book> queryByName(String bookName);
    
    @Query(value="select * from t_book order by RAND() limit ?1",nativeQuery=true)
    public List<Book> randomList(Integer num);
}

 

2, Controller写方发,写一个内部类

 注意 当new Specification<Book>() {}导包:import org.springframework.data.jpa.domain.Specification;

@RequestMapping("/list2")
public ModelAndView list2(Book book){
        ModelAndView mav = new ModelAndView();
        List<Book> bookList = bookDao.findAll(new Specification<Book>() {
            
            @Override
            public Predicate toPredicate(Root<Book> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate predicate = cb.conjunction();
                if(book!=null){
                    if(book.getName()!=null && !"".equals(book.getName())){
                        predicate.getExpressions().add(cb.like(root.get("name"), "%"+book.getName()+"%"));
                    }
                }
                if(book!=null){
                    if(book.getAuthor()!=null && !"".equals(book.getAuthor())){
                        predicate.getExpressions().add(cb.like(root.get("author"), "%"+book.getAuthor()+"%"));
                    }
                }
                return predicate;
            }
        });
        mav.addObject("bookList", bookList);
        mav.setViewName("bookList");
        return mav;
    }
        mav.addObject("bookList", bookList);
        mav.setViewName("bookList");
        return mav;
}

3,在bookAdd.ftl 中添加查询前台添加:form表单,

<form action="/book/list2" method="post">
图书名称:<input type="text" name="name"/> &nbsp; 图书作者:<input type="text" name="author"/><br/>
<input type="submit" value="查询"/>
</form>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>图书列表</title>
</head>
<body>
<a href="/bookAdd.html">添加</a>
<form action="/book/list2" method="post">
图书名称:<input type="text" name="name"/> &nbsp; 图书作者:<input type="text" name="author"/><br/>
<input type="submit" value="查询"/>
</form>
<table>
    <tr>
        <th>编号</th>
        <th>名称</th>
        <th>作者</th>
        <th>操作</th>
    </tr>
    <#list bookList as book>
    <tr>
        <td>${book.id}</td>
        <td>${book.name}</td>
        <td>${book.author}</td>
        <td>
            <a href="/book/preupdate/${book.id}">修改</a>
            <a href="/book/delete?id=${book.id}">删除</a>
        </td>
    </tr>
    </#list>
</table>
</body>
</html>

4,测试

猜你喜欢

转载自blog.csdn.net/u010393325/article/details/83957902
9.3