Search code examples
javaspring-boothibernatemavenhibernate-mapping

Hibernate one to many mapping for multiple tables


@Entity
@Table(name="Visit")
public class Visit {
    @Id
    @XmlTransient
    @JsonIgnore
    @SequenceGenerator(name = "v_id_seq", sequenceName = "v_id_seq", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "v_id_seq")
    @Column(name = "id")
    private Long id;

    @OneToMany(mappedBy = "Visit",cascade = CascadeType.PERSIST,orphanRemoval = true,fetch=FetchType.LAZY)
    private List<directions> directions;

    @OneToMany(mappedBy = "Visit",cascade = CascadeType.PERSIST,orphanRemoval = true,fetch=FetchType.LAZY)
    private List<Test> Test;

@Entity
@Table(name="test")
public class Test {
    @Id
    @XmlTransient
    @JsonIgnore
    @SequenceGenerator(name = "t_id_seq", sequenceName = "t_id_seq", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "t_id_seq")
    @Column(name = "id")
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JsonBackReference
    @JoinColumn(name = "vid", updatable = false, insertable = true,referencedColumnName = "id")
    private Visit visit;
@Entity
@Table(name="direction")
public class directions {
    @Id
    @XmlTransient
    @JsonIgnore
    @SequenceGenerator(name = "d_id_seq", sequenceName = "d_id_seq", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "d_id_seq")
    @Column(name = "id")
    private Long id;
    @ManyToOne(fetch = FetchType.LAZY)
    @JsonBackReference
    @JoinColumn(name = "vid", updatable = false, insertable = true,referencedColumnName = "id")
    private Visit Visit;

Hello i am new to hibernate I am trying to map OneToMany Visit-->Test and Visit-->direction but getting error Caused by: org.hibernate.AnnotationException: mappedBy reference an unknown target entity property:

one visit can have multiple direction and test how can i implement this?

plz help me!


Solution

  • The value of the mappedBy field on the @OneToMany annotation references java instance variable names, and it is case sensitive. You are setting it to Visit, but in the directions and test classes the variable names are visit.

    The solution is to change property mappedBy from Visit to visit (lower case V):

    @OneToMany(mappedBy = "visit",cascade = CascadeType.PERSIST,orphanRemoval = true,fetch=FetchType.LAZY)
    private List<directions> directions;
    
    @OneToMany(mappedBy = "visit",cascade = CascadeType.PERSIST,orphanRemoval = true,fetch=FetchType.LAZY)
    private List<Test> Test;