玩! JPA @ManyToMany bug

时间:2012-01-27 08:37:32

标签: hibernate jpa playframework

我有三个实体:用户团队 TeamInvite 。每个用户都有一个团队。每个用户都可以通过创建 TeamInvite 邀请其他用户加入团队。当 TeamInvite 被接受时,每个用户的 *团队*都会更新。 TeamInvites 不会影响用户,只影响他们的团队

@Entity
public class Team extends Model {
    @OneToOne
    public User user;

    @ManyToMany(cascade=CascadeType.ALL)   //I've also tried CascadeType.PERSIST
    public List<User> team = new ArrayList<User>();
}

@Entity
public class TeamInvite extends Model {
    @ManyToOne
    public User inviter;

    @ManyToOne
    public User invitee;

    public void fulfill() {
        Team team = Team.forUser(inviter);
        team.team.add(invitee);
        team.save();    //error gets thrown here

        team = Team.forUser(invitee);
        team.team.add(inviter);
        team.save();

        delete();
    }
}

调用TeamInvite.fulfill()时,出现以下错误:

PersistenceException occured : org.hibernate.exception.SQLGrammarException: could not insert collection: [models.Team.team#2]

play.exceptions.JavaExecutionException: org.hibernate.exception.SQLGrammarException: could not insert collection: [models.Team.team#2]
    at play.mvc.ActionInvoker.invoke(ActionInvoker.java:231)
    at Invocation.HTTP Request(Play!)
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not insert collection: [models.Team.team#2]
    at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1214)
    ...
Caused by: org.hibernate.exception.SQLGrammarException: could not insert collection: [models.Team.team#2]
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
    at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1243)
    at org.hibernate.action.CollectionUpdateAction.execute(CollectionUpdateAction.java:81)
    ...
Caused by: org.h2.jdbc.JdbcSQLException: Duplicate column name "TEAM_ID"; SQL statement:
insert into Team_dp_user (Team_id, team_id) values (?, ?) [42121-149]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:327)
    at org.h2.message.DbException.get(DbException.java:167)
    ...

我从Yabe演示中复制了我的注释结构(帖子有一组标签)。谁知道我做错了什么?

1 个答案:

答案 0 :(得分:3)

我猜Team.team关系的反面也被命名为User.team。如果是这样,则连接表中的列名称之间会发生冲突,因为它们的默认格式为propertyName + "_id"

因此,您需要更改其中一个属性名称,或使用@JoinTable覆盖默认列名。