Self @ManytoMany关系,完整性约束违规

时间:2015-12-14 11:00:49

标签: java database jpa playframework

我正在使用Play framewor k,我正在尝试使用jpa设置数据库方案,其中表与自身有多对多的关系。

以下是我的实体的样子:

@Entity
public class User2 extends Model{
    public static Finder<Long, User2> find = new Finder<>(User2.class);

    @Id
    public Long id;

    @Column(unique=true)
    public long twitterId;

    @JoinTable(name = "following", joinColumns = {
    @JoinColumn(name = "idFollower", referencedColumnName = "id", nullable = false)},
    inverseJoinColumns = {    @JoinColumn(name = "idFollowing", referencedColumnName = "id", nullable = false)})
    @ManyToMany
    public List<User2> followingCollection = new ArrayList<>();
}

相关测试:

public class User2Test {

    Application fakeApplication = Helpers.fakeApplication(Helpers.inMemoryDatabase());

    @Test
    public void testManyToMany(){

        running(fakeApplication, () -> {
            User2 u = new User2();
            u.twitterId = 123456L;

            User2 u2 = new User2();
            u2.twitterId = 123457L;

            u.save();
            u2.save();

            u.followingCollection.add(u2);
            u.save();

            User2 u3 = User2.find.where().eq("twitterId", 123456L).findUnique();
            Assert.assertEquals(u3.followingCollection.size(), 1);

            u.delete();
            u2.delete();
            u3 = User2.find.where().eq("twitterId", 123456L).findUnique();
            Assert.assertNull(u3);

            u3 = User2.find.where().eq("twitterId", 123457L).findUnique();
            Assert.assertNull(u3);

        });
    }

}

但是当我尝试运行测试时,我收到以下错误:

Caused by: org.h2.jdbc.JdbcSQLException: Referential integrity constraint violation: "FK_FOLLOWING_USER2_01: PUBLIC.FOLLOWING FOREIGN KEY(IDFOLLOWER) REFERENCES PUBLIC.USER2(ID) (1)"; SQL statement:
delete from user2 where id=? [23503-187]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
    at org.h2.message.DbException.get(DbException.java:179)
    at org.h2.message.DbException.get(DbException.java:155)
    at org.h2.constraint.ConstraintReferential.checkRow(ConstraintReferential.java:426)
    at org.h2.constraint.ConstraintReferential.checkRowRefTable(ConstraintReferential.java:443)
    at org.h2.constraint.ConstraintReferential.checkRow(ConstraintReferential.java:318)
    at org.h2.table.Table.fireConstraints(Table.java:920)
    at org.h2.table.Table.fireAfterRow(Table.java:938)
    at org.h2.command.dml.Delete.update(Delete.java:100)

基本理念是:

  • 我有很多用户
  • 用户可以关注其他用户
  • 在最好的世界中,删除用户也会删除其关注者列表,但不会删除关注者本身....

到目前为止,我尝试过但没有成功:   - 在连接表中反转以下/关注者关系   - 添加级联类型ALL

在我看来,联接表拒绝删除现有用户的关系。我已经阅读了很多教程,including this one但到目前为止我还没有成功。

如何在删除用户时避免遇到问题?

谢谢,

0 个答案:

没有答案