Buhake Sindi
Buhake Sindi

Reputation: 89169

Mapping keys in JPA: Primary key is a foreign key

Suppose you have a table as follows:

CREATE TABLE IF NOT EXISTS CREDENTIAL (
    USER_NAME       VARCHAR(20) NOT NULL,
    HASHED_PASSWORD VARCHAR(128) NOT NULL,
    CREATION_DATE       TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    LAST_UPDATE_DATE    TIMESTAMP,
    LAST_UPDATED_BY VARCHAR(20),

    PRIMARY KEY (USER_NAME),
    FOREIGN KEY (USER_NAME) REFERENCES USER(USER_NAME),
    FOREIGN KEY (LAST_UPDATED_BY) REFERENCES USER(USER_NAME)
) CHARACTER SET utf8;

One can see that the USER_NAME column is the primary key to the table as well as a foreign key. Yes, MySQL generates this table successfully.

The question is simple, how will I map this in JPA Entity? Should I have 1 id that maps to the USER_NAME column and another field User user that joins the USER_NAME column? Suggestions are welcome.

Upvotes: 1

Views: 7267

Answers (1)

WeMakeSoftware
WeMakeSoftware

Reputation: 9162

The simple solution would be:

@Entity
public class Credential {

    @Id
    private String userName;

    @ManyToOne
    @JoinColumn(name = "user_name")
    private User owner;

    @ManyToOne
    @JoinColumn(name = "last_modified_by")
    private User lastUpdatedBy;


}

Note from own experience:

I would recommend creating a surrogate primary key of numeric type (beneficial from the DB perspective). You can enforce the uniqueness of the username by DB constraint.

Upvotes: 2

Related Questions