发布课程 一对多映射 使用id的复合主键 当我获取获取请求的请求时,我得到空指针异常
@Entity
@Table(name = "posts")
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
@Size(max = 100)
@Column(unique = true)
private String title;
@NotNull
@Size(max = 250)
private String description;
@NotNull
@Lob
private String content;
@NotNull
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "posted_at")
private Date postedAt = new Date();
@NotNull
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "last_updated_at")
private Date lastUpdatedAt = new Date();
@OneToMany(cascade = CascadeType.ALL,
fetch = FetchType.LAZY,
mappedBy = "post")
private Set<Comment> comments = new HashSet<>();
public Post() {
}
public Post(String title, String description, String content) {
this.title = title;
this.description = description;
this.content = content;
}
//getters and setters
}
评论课 使用@Idclass
进行多对一复合主键映射@Entity
@IdClass(CommentId.class)
@Table(name = "comments")
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
@Lob
private String text;
@Id
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "post_id", nullable = false)
private Post post;
public Comment() {
}
public Comment(String text) {
this.text = text;
}
//getters and setters
}
Id类 CommentId
public class CommentId implements Serializable {
private static final long serialVersionUID = 1L;
private Post post;
private Long id;
public CommentId(Post post, Long id) {
super();
this.post = post;
this.id = id;
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result+ ((post == null) ? 0 : post.hashCode());
result = prime * result ;
return result;
}
public boolean equals(Object object) {
if (object instanceof CommentId) {
CommentId pk = (CommentId)object;
return id.equals(pk.id) && post == pk.post;
} else {
return false;
}
}
//getters and setters
}
存储库 PostRepository CommentRepository
@Repository
public interface PostRepository extends JpaRepository<Post, Long> {
}
@Repository
public interface CommentRepository extends JpaRepository<Comment, Long>
{
}
Controller类获取请求,我正在使用mysql数据库
@RestController
@RequestMapping("/demo")
public class Controller {
@Autowired
PostRepository ps;
CommentRepository cs;
@GetMapping("/post")
public List<Post> getAll(){
return ps.findAll();
}
@GetMapping("/comment")
public List<Comment> getAllcom(){
return cs.findAll();
}
}