Hibernate不会创建我的Join条目

时间:2013-11-05 20:43:01

标签: java mysql hibernate

我在hibernate中的问题是,当我想在创建新社区时将成员插入社区时,它不会插入到DB中。我哪里错了?

我的社区课程:

@Entity
@Table(name = "community")
public class Community extends BaseModel implements Serializable {
    private static final long serialVersionUID = -3290182848857364839L;

    @Column(name = "name")
    private String name;

    @Column(name = "description")
    private String description;

    @ManyToOne
    @JoinColumn(name = "owner_id", nullable = false)
    private User owner;

    @Column(name = "picture")
    private String picture;

    @ManyToMany(fetch = FetchType.LAZY, cascade = { CascadeType.ALL })
    @JoinTable(name = "community_member", joinColumns = @JoinColumn(name = "community_id"), inverseJoinColumns = @JoinColumn(name = "user_id"), uniqueConstraints = @UniqueConstraint(columnNames = {
            "user_id", "community_id" }))
    private List<User> members = new ArrayList<User>();

    //getters and setters...

我的代码:

Community community = new Community();
community.setName(name);
community.setDescription(description);
community.setOwner(user);

String fileName = saveFile(file);
community.setPicture(fileName);

community.getMembers().add(user);

this.getHibernateTemplate().save(community);

我可以看到在DB中创建了一个社区,有一个用户已经存在于DB中,但community.getMembers().add(user);不起作用。它应该在community_member表中创建一个新条目。

是不是因为我没有为community_member表创建一个java类?

编辑:我添加了用户实体。

@Entity
@Table(name = "user")
public class User extends BaseModel implements Serializable {
    private static final long serialVersionUID = 8464105544313686923L;

    @Column(name = "username", unique = true, nullable = false)
    private String username;

    @Column(name = "email", unique = true, nullable = false)
    private String email;

    @Column(name = "name", nullable = true)
    private String name;

    @Column(name = "surname", nullable = true)
    private String surname;

    @Column(name = "password", nullable = false)
    private String password;

    @Column(name = "rating", nullable = false)
    private Long rating = 0L;

    @Column(name = "picture")
    private String picture;

    @OneToOne(fetch = FetchType.EAGER, cascade = { CascadeType.ALL }, mappedBy = "user")
    private UserRole role;

    @Enumerated(EnumType.STRING)
    @Column(name = "status", nullable = false)
    private UserStatus status = UserStatus.DEACTIVE;

Edit2:答案不应该是这样的,但这是我对这个问题的解决方案(解决方法):在我在DB中创建社区后,我向社区添加了成员​​。然后我更新了社区并插入了成员。

1 个答案:

答案 0 :(得分:0)

可能存在两个问题:

  1. 您可能正在从HttpSession中添加 transient 用户,而不是当前会话中的有效持久性实例。确保正确设置用户的ID /主键,和/或尝试在当前会话中检索它。

  2. 将实体添加到“反向”关系不会在数据库中存储关系,只有关系的“主”方面才会这样做。这看起来并不像你在这里定义的那样,但这是值得注意的。