JPA多条件查询+分页+局部刷新

本文详细介绍了在Java Spring Boot框架中如何实现基于实体类的多条件查询及分页功能,包括实体类定义、DAO层接口设计、Service层实现以及Controller层的调用过程,同时提供了具体的代码示例。

使用多条件查询:
①实体类

//标明为实体类
@Entity
//命名为一张表,如果DB中没有则添加一张表,若有则更新字段,
//name可以设置表名,若不设置,则与类同名
@Table(name="t_collection")
public class Collect {
	//标明为主键
    @Id
    //自动增长(其中的一种写法)
    @GeneratedValue
    private Long id;
    private Long userid;
    private Long blogid;
    private String title;
    public Collect()
    {}

    public Long getId() {
        return id;
    }

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

    public Long getUserid() {
        return userid;
    }

    public void setUserid(Long userid) {
        this.userid = userid;
    }

    public Long getBlogid() {
        return blogid;
    }

    public void setBlogid(Long blogid) {
        this.blogid = blogid;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    @Override
    public String toString() {
        return "Collection{" +
                "id=" + id +
                ", userid=" + userid +
                ", blogid=" + blogid +
                ", title='" + title + '\'' +
                '}';
    }
}

②dao层

//写一个Repository 继承JpaRepository<Collect,Long> , JpaSpecificationExecutor<Collect> 两个
//第一个是用来调用JPA封装好的sql语句,第二个是主角-多条件查询构造器,多条件查询的封装
public interface CollectRepository extends JpaRepository<Collect,Long> , JpaSpecificationExecutor<Collect> {
    Collect findCollectByBlogidAndUserid(Long blogid, Long userid);
    void deleteCollectByBlogidAndUserid(Long blogid, Long userid);
}

③service层

写一个Service接口,同样的,如果是只是多条件查询,可以不写里面的方法。
public interface CollectService {
    Collect checkCollect(Long blogid, Long userid);
    Page<Collect> listCollection(Pageable pageable, Long id);
    void delectcollect(Long blogid, Long userid);
}

④service层实现
由于篇幅有限,去掉了其他的方法实现,留下了今天的主角

//标注为Service 并实现CollectService接口
@Service
public class CollectServiceImpl implements CollectService{
    @Autowired
    CollectRepository collectRepository;

   //能进行多条件查询并且还能分页
    @Override
    public Page<Collect> listCollection(Pageable pageable, Long id) {
		//直接调用findAll方法然后new一个 Specification<Collect>() 匿名内部类,然后重写实现Predicate toPredicate(Root<Collect> root, CriteriaQuery<?> cq, CriteriaBuilder cb)方法
        return collectRepository.findAll(new Specification<Collect>() {
			//Root是根结点,可以访问所有的类,所以给一个类泛型创建一个root就可以使用给定类的对象了。        CriteriaBuilder 参数用来确定是模糊查询还是精确查询
            @Override
            public Predicate toPredicate(Root<Collect> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                System.out.println("toPredicate:");
                List<Predicate> predicates=new ArrayList<>();
                predicates.add(cb.equal(root.<Long>get("userid"),id));
                cq.where(predicates.toArray(new Predicate[predicates.size()]));
                return null;
            }
        },pageable);
    }
}

搞定: 只需要在Controller中调用即可,可以通过Model创建一个model,调用addAttribute()方法加入到model中,从前端获取出来进行分页操作。

搭配上:

①下一页按钮 js传递一个请求

function loaddata() {
        $("#table-container").load(/*[[@{/admin/blogs/search}]]*/"/collect1",{
            title : $("[name='title']").val(),
            blogId : $("[name='blogId']").val(),
            page : $("[name='page']").val()
        });
    }

②记得每一次都要调用多条件查询的方法,然后只用局部刷新即可,返回的是局部"myCollection :: collectList"

@RequestMapping("/collect1")
    public String myCollection1(@PageableDefault(size = 8, sort = {"id"}, direction = Sort.Direction.ASC) Pageable pageable, Model model,HttpSession session)
    {
        System.out.println("collect1");
        User u=(User)session.getAttribute("user");
        model.addAttribute("page", collectService.listCollection(pageable, u.getId()));
    //        System.out.println(collectService.listCollection(pageable,id));
        System.out.println("collect1 gogogo");
        return "myCollection :: collectList";
    }

③th:fragment=“collectList” 进行table局部刷新

 <table th:fragment="collectList" class="ui compact teal table">

PS:第一次进入的时候千万不要局部刷新,而是写另一个方法是直接刷新整个页面,不然只刷新局部的话,那么只会显示局部的信息,其他的外观就看不到了。

另外一个例子:

  @Override
    public Page<Blog> listBlog(Pageable pageable, BlogQuery blog) {
        return blogRepository.findAll(new Specification<Blog>() {
            @Override
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if (!"".equals(blog.getTitle()) && blog.getTitle() != null) {
                    predicates.add(cb.like(root.<String>get("title"), "%"+blog.getTitle()+"%"));
                }
                if (blog.getTypeId() != null) {
                    predicates.add(cb.equal(root.<Type>get("type").get("id"), blog.getTypeId()));
                }
                if (blog.isRecommend()) {
                    predicates.add(cb.equal(root.<Boolean>get("recommend"), blog.isRecommend()));
                }
                cq.where(predicates.toArray(new Predicate[predicates.size()]));
                return null;
            }
        },pageable);
    }

还有一种:

  @Override
    public Page<Blog> listBlog(Pageable pageable, BlogQuery blog) {
        return blogRepository.findAll(new Specification<Blog>() {
            @Override
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if (!"".equals(blog.getTitle()) && blog.getTitle() != null) {
                    predicates.add(cb.like(root.<String>get("title"), "%"+blog.getTitle()+"%"));
                }
                if (blog.getTypeId() != null) {
                    predicates.add(cb.equal(root.<Type>get("type").get("id"), blog.getTypeId()));
                }
                if (blog.isRecommend()) {
                    predicates.add(cb.equal(root.<Boolean>get("recommend"), blog.isRecommend()));
                }
                //通过and方法拼接两个Predicate;
                cb.and(cb.like(root.<String>get("title"), "%"+blog.getTitle()+"%"),cb.equal(root.<Type>get("type").get("id"), blog.getTypeId()));
                cq.where(predicates.toArray(new Predicate[predicates.size()]));
                return null;
            }
        },pageable);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值