Search code examples
spring-boothibernatespring-data-jpahibernate-mapping

Map primary key to composite key in JPA


I have 2 tables namely user & user_session.

User table has user_id as a primary key which is referrers to user_session table.

Plus user_session has composite key including session_intime and user_id.

I have designed my entity in JPA. Now I want to map these two entities. I have tried to map these two tables. But my application build failed. Can you please help me out?

@Entity
@Table(name="user")
public class User {
    @Id
    @Email
    @Column(name = "user_id")
    private String userId;

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

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

    @OneToMany(fetch = FetchType.LAZY)
    @JoinColumn(name = "userId", referencedColumnName = "user_id")
    private UserSession userSession;
}

@Entity
@Table(name="user_session")
public class UserSession{
    @EmbeddedId
    private UserSessionPK userSessionPK;

    @Column(name = "remote_ip")
    private String remoteIp;
}

@Embeddable
public class UserSessionPK implements Serializable {
    private static final long serialVersionUID = 1L;

    @Column(name = "user_id")
    private String userId;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "time_in")
    private Date timeIn;
}

I want to map user_id of User table to user_id of UserSessionPK. I am new to JPA, so I don't know how to map with embeddable class.


Solution

  • Remove the mappedBy attribute. This attribute is used when you have bidirectional relationship to indicate which side of the relationship is the owner.

    But you will need to set the Foreign Key aka JoinColumn

    @JoinColumn("user_id")
    @OneToMany(fetch = FetchType.LAZY)
    private UserSession userSession;