Hibernate多对多连接表没有填充

时间:2015-07-09 11:43:00

标签: hibernate jpa orm many-to-many

我想通过使用连接表的多对多关联将两个实体类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表添加任何内容。我在这里错过了什么? 干杯, 克里斯

2 个答案:

答案 0 :(得分:0)

我认为您应该在$("#your_form_id").html("<div><p>You have submitted the form successfully.</p></div>")班级和User班级中指定您的ID,以匹配将加入Unit注释的属性。

您可以同时添加@JoinColumnUser个类吗?

Unit

答案 1 :(得分:0)

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

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