如何创建没有主键的Spring实体(Entity)和仓库(Repository)

huangapple go评论72阅读模式
英文:

How to create Spring Entity and Repository without primary key

问题

以下是翻译好的部分:

我有一张包含两列 user_idrole_id 的表。表中没有唯一的列,也无法添加唯一列。在没有主键的情况下,我如何在Spring中创建EntityRepository

这是我的 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解释

另一个选项是,如果这是一个关联表,那么您可以创建嵌入式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.

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;

}

huangapple
  • 本文由 发表于 2020年9月17日 19:03:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/63936676.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定