【问题标题】:question about hibernate annotations关于hibernate注解的问题
【发布时间】:2011-01-04 12:39:30
【问题描述】:

我有 2 个实体:用户和角色 我有一个类 Userrole,它将包含用户和角色之间的复合键。

现在 Userrole 将不包含 userId 和 roleId.. 但对象 User 和 Role 看起来像这样:

public class UserRole implements Serializable{
    User user;
    Role role;

我可以将@Id 放在用户上吗?喜欢:

    @Id
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }

?

【问题讨论】:

    标签: java hibernate annotations


    【解决方案1】:

    使用注解,你需要为你的复合id定义一个合适的类,并注解为@Embeddable。 (使用 XML,也可以在没有显式 id 类的情况下映射复合 id。)这里是 an example using an inner class 作为复合 id,another one, with a top-level id class。

    【讨论】:

      【解决方案2】:

      没有。 您只能在原语中使用 @Id。但是您可以使用@ComposeId 或@IdClass(类似的东西,现在无法访问休眠文档...)并将用户映射为您的组合ID

      【讨论】:

        【解决方案3】:

        我会做的方式:

            @Entity
            public class User {
            ...
            @OneToMany
            public Set<UserRoles> getUserRoles() {
                    return this.userRoles;
                }
            }
        
            @Entity
            public class UserRole {
            ...
        
            @Id 
            @GeneratedValue
            public long getId() {
                           return this.id;
           }
        
            @ManyToOne
            public Role getRole() {
                    return this.role;
                }
        
        
            @ManyToOne
            public Role getCategory() {
                    return this.category;
                }
        
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-03-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-06-25
          • 2012-06-03
          • 1970-01-01
          相关资源
          最近更新 更多