Home > Software engineering >  Hibernate Relationships with inheritance
Hibernate Relationships with inheritance

Time:11-18

I have 4 classes. Entry, EntryTypeOne, EntryTypeTwo and ExampleClass

@Getter
@Setter
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="entryType",
        discriminatorType = DiscriminatorType.STRING)
public class Entry {
    @Id
    @GeneratedValue
    protected Long id;

    @Column(nullable = false)
    protected String title;

    @Column(nullable = false)
    protected String description;
}
@Getter
@Setter
@Entity
@DiscriminatorValue("One")
public class EntryTypeOne extends Entry{

    @ManyToMany(cascade = CascadeType.ALL)
    private List<ExampleClass> exampleClasses;
}
@Getter
@Setter
@Entity
@DiscriminatorValue("Two")
public class EntryTypeTwo extends Entry{

    @ManyToMany(cascade = CascadeType.ALL)
    private List<ExampleClass> exampleClasses;
}
@Getter
@Setter
@Entity
public class ExampleClass {

    @Id
    @GeneratedValue
    private Long id;

    @ManyToMany(mappedBy = "exapmleClasses")
    private List<Entry> entries;
}

When I start this I get this error:

nested exception is org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: ch.musiciansearch.vingrn.entity.Entry.exampleClasses in ch.musiciansearch.vingrn.entity.ExampleClass.entries

My Goal is to make a DB like this: DBIMAGE

Can I do this without implementing two Lists with the EntryTypes (1 for entrytypeone and 1 for entrytypetwo)?

CodePudding user response:

You are not using the @ManyToMany annotation in a correct way. Here's how you do ... imagine you have a Student entity and Course entity.

And students like some courses and don't like others. You want to store information about liked courses in the DB. Here's how you do ...

class Student {

// OK, so student class will be the owner of the relationship
// Here we describe the join table, which stores many-to-many data in the DB
@ManyToMany
@JoinTable(
  name = "course_like", 
  joinColumns = @JoinColumn(name = "student_id"), 
  inverseJoinColumns = @JoinColumn(name = "course_id"))
Set<Course> likedCourses;
}

And for course class you do like this ...

// Just add a simple mapped by followed by the name of the field in the owning entity
@ManyToMany(mappedBy = "likedCourses")
Set<Student> likes;

Does this solve your problem ? Let me know in the comments.

  • Related