【问题标题】:Hibernate many-to-many join table not populating休眠多对多连接表未填充
【发布时间】:2015-09-27 18:23:51
【问题描述】:

我想通过使用连接表的多对多关联来关联两个实体类 User 和 Unit。然而,这并没有按预期工作。首先,我将简要地向您展示我到目前为止所获得的内容。

数据库:

|    User    |   |  UserToUnit   |   |   Unit    |
|Id|login|...|   |User_Id|Unit_Id|   |Id|name|...|

实体用户:

    @Entity
    @Table(name = "\"User\"")
    public class User implements Identifiable {
        public User() {
            units = new ArrayList<Unit>();
        }

        @Id
        @GeneratedValue(generator = "increment")
        @GenericGenerator(name = "increment", strategy = "guid")
        @Column(name = "Id", columnDefinition = "uniqueidentifier")
        private String id;

        @Transient
        @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
        @JoinTable(name = "UserToUnit",
            joinColumns = { @JoinColumn(name = "User_Id", nullable = false, updatable = false) },
            inverseJoinColumns =  { @JoinColumn(name = "Unit_Id", nullable = false, updatable = false) }
        )
        private Collection<Unit> units;
        [...]
        public Collection<Unit> getUnits() {
            return units;
        }

        public void setUnits(Collection<Unit> ous) {
            units= ous;
        }
    }

实体单位:

@Entity
@Table(name = "Unit")
@XmlRootElement
public class Unit implements Identifiable {

public Unit() {
    users = new ArrayList<User>();
}

@Id
@GeneratedValue(generator = "increment")
@GenericGenerator(name = "increment", strategy = "guid")
@Column(name = "Id", columnDefinition = "uniqueidentifier")
private String id;

@Transient
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "units")
private Collection<User> users;
[...]
public Collection<User> getUsers() {
    return users;
}

public void setUsers(Collection<User> us) {
    users = us;
}

用法:

user.getUnits().add(unit);
unit.getUsers().add(user);
unitDAO.saveOrUpdate(unit);
userDAO.saveOrUpdate(user);

但这不会向 UserToUnit 表添加任何内容。我在这里想念什么? 干杯, 克里斯

【问题讨论】:

    标签: hibernate jpa orm many-to-many


    【解决方案1】:

    我认为您应该在 User 类和 Unit 类中指定您的 ID,以匹配将在 @JoinColumn 注释中加入的属性。

    你能把这个添加到UserUnit 类吗?

    @Id
    @Column(name = "Id")
    private long id;
    

    【讨论】:

    • 那是在“[...]”中,为了节省空间我省略了。在休眠状态下,您不能拥有没有 Id 的实体。
    • 哦,好的。您的 User 和 Unit 实体是否有效,或者您遇到与 UserToUnit 相同的问题?
    • 在我的代码示例中添加了 Id 属性。是的,各个实体也可以工作。
    【解决方案2】:

    您使用@Transient 注释的原因是什么?如果您想使用属性访问并且 getter 未遵循字段名称,则应该使用它。

    您正在混合使用字段和属性访问,因此您还应该将 @Access(AccessType.PROPERTY) 添加到 getter 方法或将注释移动到字段。

    【讨论】:

    • @Transient 用于将实体序列化为 JSON 时的 JAXB。我不明白你的第二个说法。请展开。谢谢。
    • 我把注释误认为 javax.persistence.Transient 这意味着该字段不会被持久化。你不是说 javax.xml.bind.annotation.XmlTransient 吗?我还可以看到您已将注释移至该字段,因此我的第二条评论现在无关紧要。
    • 非常感谢!你说的对。有点。我把 @Transient 误认为是 @XmlTransient 注释。加油!
    猜你喜欢
    • 2016-01-09
    • 2012-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-20
    • 1970-01-01
    • 2016-06-13
    • 1970-01-01
    相关资源
    最近更新 更多