Home > Back-end >  JPA do not allow binary one to many relationship
JPA do not allow binary one to many relationship

Time:02-28

I have 2 entities as below:

Course

@Entity
public class Course {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @OneToMany(mappedBy = "course", cascade = {CascadeType.PERSIST, CascadeType.REMOVE, CascadeType.MERGE})
    private List<Comment> comments;

Comment

@Entity
public class Comment {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String comment;

   @ManyToOne(targetEntity = Course.class)
   private Course course; //Error: 'Many To One' attribute type should not be 'Course' 

I follow luv2code.com course but he use Spring MVC and it work just find, but when I do this in spring boot, it always show the error, please help me fix this!

CodePudding user response:

Try something like this:

@Entity
public class Course {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @OneToMany(mappedBy = "course")
    private List<Comment> comments;

And your comment entity:

@Entity
public class Comment {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String comment;

   @ManyToOne(cascade = CascadeType.ALL)
   private Course course;

CodePudding user response:

    @Entity
    public class Course {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @OneToMany(cascade = CascadeType.ALL,
            fetch = FetchType.LAZY,
    orphanRemoval = true)
    private List<Comment> comments = new ArrayList<Comment>();


    @Entity
    public class Comment {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String comment;
}

You don't to define ManyToOne Mapping in your comment Entity.

  • Related