8

我正在使用最新版本的 playframework (2.0.4) 和 Ebean ORM。这是我的简化数据库架构

TABLENAME (FIELD_NAME (, ...) )
User (id)
Group (id)
UserGroup (user_id, group_id, is_active)

我想创建我的实体模型,如下所示:

@Entity
public class UserGroup extends Model {
    private static final long serialVersionUID = 1L;

    @EmbeddedId
    public UserGroupPK pk;
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id", insertable = false, updatable = false)
    public User user;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "group_id", insertable = false, updatable = false)
    public Group group;
}

@Embeddable
public class UserGroupPK implements Serializable{
    private static final long serialVersionUID = 1L;

    public Long userId;
    public Long groupId;

    public UserGroupPK(Long userId, Long groupId) {
        this.userId = userId;
        this.groupId = groupId;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final UserGroupPK other = (UserGroupPK) obj;
        if ((this.userId == null) ? (other.userId != null) : !this.userId.equals(other.userId)) {
                return false;
            }
        if ((this.groupId == null) ? (other.groupId != null) : !this.groupId.equals(other.groupId)) {
            return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 89 * hash + (this.userId != null ? this.userId.hashCode() : 0);
        hash = 89 * hash + (this.groupId != null ? this.groupId.hashCode() : 0);
        return hash;
    }
}

适合你吗。如果这个中间表没问题,那么 User 和 Group 实体呢?提前致谢。

4

1 回答 1

4

一些注释似乎不正确,但无论如何都可以工作。

如果我是你,我会这样做:

@Embeddable
public class UserGroupPK implements Serializable{
    private static final long serialVersionUID = 1L;

    @Column(name = "user_id")
    public Long userId;
    @Column(name = "group_id")
    public Long groupId;

对于多对一列:

@ManyToOne
@JoinColumn(name = "user_id", referenceColumnName = "id", nullable = false) // insertable and updatable by default are true, which I think are correct here
public User user;

// same for group

在您的用户实体中,您需要以下内容:

@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
public Set<UserGroup> groups

当你找到时,就像

// find all users within a certain group
Ebean.find(User.class)
     .fetch("groups")
     .where().eq("groups.groupId", "...").findList();
于 2014-04-06T21:47:57.003 回答