bici
bici

Reputation: 47

How to create Spring Entity and Repository without primary key

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.

Upvotes: 0

Views: 9159

Answers (1)

I_AM__PAUL
I_AM__PAUL

Reputation: 138

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;

}

Upvotes: 1

Related Questions