1

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

我的社区课:

@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);

我可以看到在数据库中创建了一个社区,数据库中已经存在一个用户,但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 中创建社区后,我将成员添加到社区。然后我更新了社区并插入了成员。

4

1 回答 1

0

可能存在以下两个问题之一:

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

  2. 将实体添加到“反向”关系不会将关系存储在数据库中,只有关系的“主”端会这样做。它看起来不像您在这里定义为逆,但这是需要注意的。

于 2013-11-06T00:14:03.047 回答