1、在实体类中添加新的变量与set、get函数
news类中添加如下变量与其相应的set和get函数
@ManyToMany(cascade = CascadeType.PERSIST)//级联 多对多会生成中间表news-tas private List<Tag> tags=new ArrayList<>(); @Transient private String tagIds;//不生成字段 private String description;
tag类
@ManyToMany(mappedBy = "tags") private List<News> newsList=new ArrayList<>();
2、创建一个用于后端查询数据的类,包含三个属性
private String title; private Long typeId; private boolean recommend;
3、新建NewService接口
public interface NewService { Page<News> listNew(Pageable pageable, NewQuery newQuery); News saveNews(News news); News getNew(Long id); News updateNew(Long id, News news); }
4、新建NewsDAO接口,继承自JpaRepository<News,Long>, JpaSpecificationExecutor<News>
public interface NewRepository extends JpaRepository<News,Long>, JpaSpecificationExecutor<News> {
}
5、新建NewServiceImpl类实现NewService接口中的方法;以列表查询为例
//新闻管理中的列表(包含了查询)
@Override
public Page<News> listNew(Pageable pageable, NewQuery newQuery) {
return newRepository.findAll(new Specification<News>() {
@Override
public Predicate toPredicate(Root<News> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
List<Predicate> predicates=new ArrayList<>();
if(!"".equals(newQuery.getTitle()) && newQuery.getTitle()!=null){
predicates.add(cb.like(root.<String>get("title"),"%"+newQuery.getTitle()+"%"));
}
if(newQuery.getTypeId()!=null){
predicates.add(cb.equal(root.get("type").get("id"),newQuery.getTypeId()));
}
if(newQuery.isRecommend()){
predicates.add(cb.equal(root.get("recommand"),newQuery.isRecommend()));
}
cq.where(predicates.toArray(new Predicate[predicates.size()]));
return null;
}
},pageable);
}
6、创建NewController类,用于实现前后端数据交互;以更新为例
@GetMapping("/news/{id}/toUpdate") public String toUpdate(@PathVariable Long id, Model model){ setTypeAndTag(model); News news=newService.getNew(id); news.init(); model.addAttribute("news",news); return INPUT; }
7、在News实体类中创建init和tagsToIds函数用于实现更新功能
public void init(){ this.tagIds=tagsToIds(this.getTags()); } private String tagsToIds(List<Tag> tags) { if(!tags.isEmpty()){ StringBuffer ids= new StringBuffer(); Boolean flag=false; for(Tag tag:tags){ if(flag){ ids.append(",");}else{flag=true;} ids.append(tag.getId());} return ids.toString();}else{return tagIds; } }
8、在TagService接口中添加listTag,并在Impl中进行实现用于实现提交功能
public List<Tag> listTag() { return tagRepository.findAll(); } public List<Tag> listTag(String ids) { return tagRepository.findAllById(convertToList(ids)); } private List<Long> convertToList(String ids){ System.out.println("service接收TagId为"+ids); List<Long> list=new ArrayList<>(); if(!"".equals(ids) && ids!=null){ String[] idArray=ids.split(","); for(int i=0;i<idArray.length;i++){ list.add(new Long(idArray[i])); } } System.out.println("service处理完后TagId为"+list); return list; }
原文:https://www.cnblogs.com/dragon-wxl/p/13399971.html