条件查询与分页展示
1.Tag实体类新增属性,构造相应get,set函数
@ManyToMany(mappedBy = "tags")
private List<News> newsList = new ArrayList<>();
2.News中新增属性,构造相应get,set函数,改变toString函数
@ManyToMany(cascade = CascadeType.PERSIST) //级联
private List<Tag> tags = new ArrayList<>();
@Transient
private String tagIds;
private String description;
3.创建vo包,VO是指value object值对象,通常用于业务层之间的数据传递,和PO一样也是仅仅包含数据而已。一般来说,PO只能用在数据层,VO用在商业逻辑层和表示层。在vo包下创建NewsQuery类,我们利用NewsQuery类专门处理新闻管理界面的条件查询。因为我们需要通过新闻的标题、类型以及是否被推荐作为条件来查询数据库里的新闻,所以我们就利用这三个属性来组成一个查询类。
public class NewQuery {
private String title;
private Long typeId;
private boolean recommend;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Long getTypeId() {
return typeId;
}
public void setTypeId(Long typeId) {
this.typeId = typeId;
}
public boolean isRecommend() {
return recommend;
}
public void setRecommend(boolean recommend) {
this.recommend = recommend;
}
@Override
public String toString() {
return "NewQuery{" +
"title='" + title + '\'' +
", typeId=" + typeId +
", recommend=" + recommend +
'}';
}
}
4.新建NewService接口
public interface NewService {
//新闻管理页面,组合条件查询
Page<News> listNew(Pageable pageable, NewQuery newQuery);
}
5.新建NewServiceImpl类,实现上面接口
@Service
public class NewServiceImpl implements NewService {
@Autowired
private NewRepository newRepository;
//新闻管理中的列表(包含了查询)
@Override
public Page<News> listNew(Pageable pageable, NewQuery newQuery) {
return newRepository.findAll(new Specification<News>() {
@Override
public Predicate