0

I have a table with two columns user_id and role_id. There's no unique column in table and I can't add one. How can I create Entity and Repository in Spring without a primary key?

This is my UserRole.class

public class UserRole {
    @Column(name = "user_id")
    private int userId;
    
    @Column(name = "role_id")
    private int roleId;


    //getters and setters
}

But with this class i get the following error:

nested exception is org.hibernate.AnnotationException: No identifier specified for entity:

I saw that one of the answers is to use all of the columns as the id, but i have no idea how to do it.

Mario Codes
  • 689
  • 8
  • 15
bici
  • 47
  • 1
  • 8
  • 1
    What database are you using? Some DBs have a hidden primary key that is autogenerated and hidden. – George Sep 17 '20 at 12:43
  • 2
    Why would you need an entity for that? That is just the table used on an `@ManyToMany` relation and you don't need a specific entity for that. Just a proper mapping in your `User` and `Role` entities. – M. Deinum Sep 17 '20 at 12:45

1 Answers1

1

Please see the awnser in this post. This should help you.

PK Explained

Another Option is if this is a join table, than you could make Embeded PK

@Embeddable
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder(toBuilder = true)
public class PersonGroupPK implements Serializable {
//default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;

@Column(insertable=false,unique = false, updatable=false, nullable=false)
private Long personId;

@Column(insertable=false, unique = false,updatable=false, nullable=false)
private Long groupId;

}
I_AM__PAUL
  • 118
  • 7