Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading