英文:
How to create Spring Entity and Repository without primary key
问题
以下是翻译好的部分:
我有一张包含两列 user_id
和 role_id
的表。表中没有唯一的列,也无法添加唯一列。在没有主键的情况下,我如何在Spring中创建Entity
和Repository
?
这是我的 UserRole.class:
public class UserRole {
@Column(name = "user_id")
private int userId;
@Column(name = "role_id")
private int roleId;
//getters and setters
}
但是,使用这个类会出现以下错误:
嵌套异常为 org.hibernate.AnnotationException: 未为实体指定标识符:
我看到其中一个解决方法是将所有列用作标识符,但我不知道如何实现。
英文:
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.
答案1
得分: 1
请参考此帖子中的答案。这应该能帮助您。
另一个选项是,如果这是一个关联表,那么您可以创建嵌入式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;
}
英文:
Please see the awnser in this post. This should help you.
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;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论