SpringBoot后端开发新闻页查询+新增+编辑
程序员文章站
2022-03-27 13:45:39
SpringBoot后端开发新闻页查询+新增+编辑新建实体Dao包新建接口新建VO包Service接口Web包界面显示新建实体News.java:@Entity@Table(name = "t_news")public class News { @Id //主键标识 @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; //懒加载...
新建实体
News.java:
@Entity
@Table(name = "t_news")
public class News {
@Id //主键标识
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
//懒加载
@Basic(fetch = FetchType.LAZY)
@Lob
private String content;
private String firstPicture;
private String flag;
private String views;
private boolean appreciation;
private boolean shareStatement;
private boolean commentabled;
private boolean published;
private boolean recommend;
@Temporal(TemporalType.TIMESTAMP)
private Date createTime;
@Temporal(TemporalType.TIMESTAMP)
private Date updateTime;
@ManyToOne
private Type type;
@ManyToOne
private User user;
@Transient
private String tagIds;
private String description;
@ManyToMany(cascade = CascadeType.PERSIST) //级联
//tags名字要与Tag类中mapped by参数名相对应
private List<Tag> tags = new ArrayList<>();
public News(){}
public void init(){
this.tagIds =tagsToIds(this.getTags());
}
//将List<Tag>类型对象转化成"tagid1,tagid2,tagid3..."形式的String字符串
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;
}
}
//省略get和set方法
}
Tag.java:
@Entity
@Table(name = "t_tag")
public class Tag {
@Id //主键标识
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank(message = "标签名称不能为空")
private String name;
//mappedBy参数要与News类中List<Tag>变量名相对应
@ManyToMany(mappedBy = "tags")
private List<News> newsList = new ArrayList<>();
public Tag(){}
}
Dao包新建接口
在dao包中涉及到的接口有如下两个:
NewRepository.java:
//NewRepository.java
public interface NewRepository extends JpaRepository<News,Long>, JpaSpecificationExecutor<News> {
//只需要使用内置的方法即可
}
TagRepository.java:
//TagRepository.java
public interface TagRepository extends JpaRepository<Tag,Long> {
Tag findByName(String name);
}
新建VO包
新建vo包,然后在其目录下新建NewQuery.java类,用来辅助对应News内容较为复杂的查询
//NewQuery.java
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 +
'}';
}
}
Service接口
在Service包中编写如下接口
NewService.java:
//NewService.java
public interface NewService {
Page<News> listNew(Pageable pageable, NewQuery newQuery);
News saveNews(News news);
News getNew(Long id);
News updateNew(News news);
}
TagService.java:
//TagService.java
public interface TagService {
Page<Tag> ListTag(Pageable pageable);
Tag saveTag(Tag tag);
void deleteTag(Long id);
Tag getTagByName(String name);
Tag getTag(Long id);
Tag updateTag(Long id,Tag tag);
List<Tag> listTag();
List<Tag> listTag(String ids);
}
然后分别编写Impl类实现对应接口
NewServiceImpl.java:
//NewServiceImpl.java
@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 toPredicate(Root<News> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
List<Predicate> predicateList = new ArrayList<>();
//是否存在标题检索
if(!"".equals(newQuery.getTitle())&&newQuery.getTitle()!=null){
predicateList.add(criteriaBuilder.like(root.<String>get("title"),"%"+newQuery.getTitle()+"%"));
}
//是否分类检索
if(newQuery.getTypeId()!=null){
predicateList.add(criteriaBuilder.equal(root.get("type").get("id"),newQuery.getTypeId()));
}
//是否推荐
if(newQuery.isRecommend()){
predicateList.add(criteriaBuilder.equal(root.get("recommend"),newQuery.isRecommend()));
}
criteriaQuery.where(predicateList.toArray(new Predicate[predicateList.size()]));
return null;
}
}, (org.springframework.data.domain.Pageable) pageable);
}
@Override
public News saveNews(News news) {
if(news.getId()==null){
news.setCreateTime(new Date());
news.setUpdateTime(new Date());
}
return newRepository.save(news);
}
@Override
public News getNew(Long id) {
return newRepository.findById(id).orElse(null);
}
@Override
public News updateNew(News news) {
News news1 = newRepository.findById(news.getId()).orElse(null);
if(news1==null){
System.out.println("未获取更新对象");
}
BeanUtils.copyProperties(news,news1);
news1.setUpdateTime(new Date());
return newRepository.save(news1);
}
}
TagServiceImpl.java:
//TagServiceImpl.java
@Service
public class TagServiceImpl implements TagService {
@Autowired
private TagRepository tagRepository;
@Override
public Page<Tag> ListTag(Pageable pageable) {
return tagRepository.findAll(pageable);
}
@Override
public Tag saveTag(Tag tag) {
return tagRepository.save(tag);
}
@Override
public void deleteTag(Long id) {
tagRepository.deleteById(id);
}
@Override
public Tag getTagByName(String name) {
return tagRepository.findByName(name);
}
@Override
public Tag getTag(Long id) {
return tagRepository.findById(id).orElse(null);
}
@Override
public Tag updateTag(Long id, Tag tag) {
Tag tag1 = tagRepository.findById(id).orElse(null);
if(tag1==null){
System.out.println("未获得更新对象");
return null;
}else{
BeanUtils.copyProperties(tag,tag1);
return tagRepository.save(tag1);
}
}
@Override
public List<Tag> listTag() {
return tagRepository.findAll();
}
@Override
public List<Tag> listTag(String ids) {
return tagRepository.findAllById(converToList(ids));
}
private List<Long> converToList(String ids){
System.out.println("Service接受ids为:"+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]));
}
}
return list;
}
}
Web包
新建NewController.java类
@Controller
@RequestMapping("/admin")
public class NewController {
private static final String INPUT = "admin/news-input";
private static final String LIST = "admin/news";
private static final String REDIRECT_LIST = "redirect:/admin/news";
@Autowired
private NewService newService;
@Autowired
private TypeService typeService;
@Autowired
private TagService tagService;
@RequestMapping("/news")
public String news(@PageableDefault(size = 3,sort = {"updateTime"},direction = Sort.Direction.DESC)
Pageable pageable, NewQuery newQuery, Model model){
model.addAttribute("types",typeService.listType());
model.addAttribute("page",newService.listNew(pageable,newQuery));
return LIST;
}
@PostMapping("/news/search")
public String search(@PageableDefault(size = 3,sort = {"updateTime"},direction = Sort.Direction.DESC)
Pageable pageable, NewQuery newQuery, Model model){
model.addAttribute("page",newService.listNew(pageable,newQuery));
return "admin/news::newsList";
}
public void setTagAndType(Model model){
model.addAttribute("types",typeService.listType());
model.addAttribute("tags",tagService.listTag());
}
@GetMapping("/news/input")
public String input(Model model){
setTagAndType(model);
model.addAttribute("news",new News());
return INPUT;
}
@GetMapping("/news/{id}/toUpdate")
public String toUpdate(@PathVariable Long id,Model model){
setTagAndType(model);
News news = newService.getNew(id);
news.init();
model.addAttribute("news",news);
return INPUT;
}
@PostMapping("/news/add")
public String post(News news, RedirectAttributes attributes, HttpSession session){
news.setUser((User) session.getAttribute("user"));
news.setType(typeService.getType(news.getType().getId()));
news.setTags(tagService.listTag(news.getTagIds()));
News news1;
if(news.getId()==null){
news1 = newService.saveNews(news);
}else {
news1 = newService.updateNew(news);
}
if(news1==null){
attributes.addFlashAttribute("message","操作失败");
}else{
attributes.addFlashAttribute("message","操作成功");
}
return REDIRECT_LIST;
}
}
界面显示
新闻主界面:
新增界面:
发布成功:
通过分类搜索:
使用模糊搜索:
是否推荐搜索:
编辑界面:
本文地址:https://blog.csdn.net/qq_41823958/article/details/107680566
上一篇: 小红书开启好物推荐功能?