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.

2
  • 1
    What database are you using? Some DBs have a hidden primary key that is autogenerated and hidden. Commented Sep 17, 2020 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. Commented Sep 17, 2020 at 12:45

1 Answer 1

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;

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.