1.实体类设计
首先是Type类型,用来表示新闻的类型
package com.zr0726.news.po;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "t_type")
public class Type {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank(message = "分类名称不能为空")
private String name;
@OneToMany(mappedBy = "type")
private List<News> news = new ArrayList<>();
public Type(){
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<News> getNews() {
return news;
}
public void setNews(List<News> news) {
this.news = news;
}
@Override
public String toString() {
return "Type{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
2.功能类设计
首先实现了一个类型接口
//TypeRepository
package com.zr0726.news.dao;
import com.zr0726.news.po.Type;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TypeRepository extends JpaRepository<Type,Long> {
Type findByName(String name);
}
再开始写类型相关的服务,首先是类型功能的接口
package com.zr0726.news.service;
import com.zr0726.news.po.Type;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
public interface TypeService {
Page<Type> listType(Pageable pageable);
Type saveType(Type type);
Type getTypeByName(String name);
void delete(Long id);
Type getType(Long id);
Type updateType(Long id,Type type);
}
具体的实现逻辑如下:
package com.zr0726.news.service.impl;
import com.zr0726.news.dao.TypeRepository;
import com.zr0726.news.po.Type;
import com.zr0726.news.service.TypeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
@Service
public class TypeServiceImpl implements TypeService {
@Autowired
private TypeRepository typeRepository;
@Override
public Page<Type> listTy