Home > other >  How to map a table in Spring Data JPA that has 2 columns referencing the same table
How to map a table in Spring Data JPA that has 2 columns referencing the same table

Time:03-11

I have a table that has 2 fields (pseudonymProfile and realProfile) that both join to the same table. When I try to do the mapping as shown below, I run into an error because the 2 fields use the same name (profile_id) in their @JoinColumn annotation. I'm under the impression that when defining a join column, I need to specify the name as <jointable_primarykeyofjointable> in order for spring boot to correctly do the join, but in this case they have the same name and that causes the error. Can someone help me see what I am missing? Thanks!

@Entity
@Table(name = "book")
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private UUID id;

    @Column(name = "title")
    private String title;

    @ManyToOne
    @JoinColumn(name = "profile_id")
    private Profile pseudonymProfile;

    @ManyToOne
    @JoinColumn(name = "profile_id")
    private Profile realProfile;
}

CodePudding user response:

@ManyToOne
@JoinColumn(name = "pseudonym_profile_id", referencedColumnName = "profile_id")
private Profile pseudonymProfile;

@ManyToOne
@JoinColumn(name = "real_profile_id", referencedColumnName = "profile_id")
private Profile realProfile;

Just an example which should work. JoinColumn#referencedColumnName

But I guess if you drop those @JoinColumns at all everything should work as expected.

UPDATE:

One more thing I find really suspicious is that you use @OneToMany instead of @ManyToOne which would make more sense.

If your business logic was to support multiple profiles for one book you would have to use Collection<Profile> with @OneToMany.

  • Related