Alex Rivera | Logout

how to make a composite primary key (java persistence annotation)

Asked 2009-07-31T11:36:16.367
20

How to make it so that the table user_roles defines the two columns (userID, roleID) as a composite primary key. should be easy, just can't remember/find.

In user entity:

@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "user_roles")
public List<RoleDAO> getRoles() {
    return roles;
}

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Integer getUserID() {
    return userID;
}

In roles entity:

@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "user_roles")
public List<UserDAO> getUsers() {
    return users;
}

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Integer getRoleID() {
    return roleID;
}

Thank you.

** MORE INFO

So there is a third table user_roles (auto generated by above) that takes userID from user entity and roleID from roles entity. Now I need those two columns in the generated table (user_roles) to be a composite primary key.

Edit
Report

1 Answer

1

Thank you for improving your question ... and taking into account the suggestions.

(Sorry, It is a bit strange that you postfix your entities with Daos, but it is not the point.)

I'm not sure there is any problem left :

  • The two entities you describe each have one PK, not a pair-of.
  • The link-table has no corresponding entity, it is defined implicitely by the two entities and their ManyToMany relationship. If you need a third Entity, change your ManyToMany for a pair of OneToMany and ManyToOne relationships.
answered 2009-07-31T12:40:23.277

Your Answer