Home JPA / Hibernate: create a primary key which is a primary key of another table
Reply: 1

JPA / Hibernate: create a primary key which is a primary key of another table

Andrea Bevilacqua
1#
Andrea Bevilacqua Published in 2018-02-12 12:05:26Z

I have this simple User entity:

@Entity
@Table(name = "fdei_user")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String login;
}

I would like to create a second table UserDetail with fields id and property1.

In this the second table UserDetail I do not want a generated incremented id, but I want that the field id is the same id of the user in the table User, and I want that when I fetch the UserDetail id=1, also the User entity with id=1 is fetched.

@Entity
@Table(name = "fdei_user_details")
public class UserDetails {

    @Id
    @OneToOne
    @PrimaryKeyJoinColumn(name="id", referencedColumnName="id")
    private User id;

    private Boolean property1;
}

How can I realize this? I tried with @OneToOne, @PrimaryKeyJoinColumn, @MapsId...but nothing...I always have errors.

What's the right way?

Thanks a lot, Andrea

Lesiak
2#
Lesiak Reply to 2018-02-12 12:49:31Z
  • What you are looking for is Unidirectional @OneToOne relationship.
  • You need both @Id field and a relationship (User user) field.
  • Please note the usage of @MapsId to make sure that there is only one key field in the details table.

I added this answer, as none of the sources posted in comments had reference to @MapsId

@Entity
@Table(name = "fdei_user_details")
public class UserDetails {

    @Id
    @Column(name = "id", updatable = false, nullable = false)
    private Long id;

    @MapsId
    @OneToOne
    @JoinColumn(name = "id", referencedColumnName = "id")
    private User user;

    private Boolean property1;

    // getters and setters
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.324379 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO