How to use mapping table for @OneToMany and @ManytoOne bidirectional relationship?

38 Views Asked by At

I have 2 tables - Group, Expense. My requirement is that I want to establish bidirectional relationship between Group and Expense using external mapping table. The relationship from Group to Expense is @OneToMany. Below are my Group and Expense classes.

@Entity
@Table(name = "GROUP")
public class Group {
    @Id
    @GeneratedValue(generator = "group-generator")
    @GenericGenerator(name = "group-generator",
            parameters = @Parameter(name = "prefix", value = "g"),
            type = SplitwiseIdGenerator.class)
    @Column(name = "ID")
    private String id;
 
    // other attributes...
 
    @OneToMany(mappedBy = "group")
    private List<Expense> expenses;
}
@Entity
@Table(name = "EXPENSE")
public class Expense {
    @Id
    @GeneratedValue(generator = "expense-generator")
    @GenericGenerator(name = "expense-generator",
            parameters = @Parameter(name = "prefix", value = "e"),
            type = SplitwiseIdGenerator.class)
    @Column(name = "ID")
    private String id;
 
    // other attributes...
 
    @ManyToOne
    @JoinTable(name = "GROUP_EXPENSE",
            joinColumns = {@JoinColumn(name = "EXPENSE_ID")},
            inverseJoinColumns = {@JoinColumn(name = "GROUP_ID")})
    private Group group;
}

I am auto creating tables with spring.jpa.hibernate.ddl-auto=update. The above relationship is not working as I am getting below error during Spring startup Caused by: org.hibernate.AnnotationException: Secondary table 'group_expense' for property 'org.vip.splitwise.models.Expense' is not declared (use '@SecondaryTable' to declare the secondary table).

These are my expected db tables.

enter image description here

Anyone please help me on this. Thanks in advance.

0

There are 0 best solutions below