java 违反完整性约束

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4420516/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 06:17:21  来源:igfitidea点击:

Integrity constraint violation

javahibernatejpaplayframework

提问by Jason Miesionczek

Using the Play! Framework, i have the following two models:

使用播放!框架,我有以下两个模型:

@Entity
public class User extends Model {
    public String firstName;
    public String lastName;
    public String email;
    public String password;
    public boolean isAdmin;

    @OneToMany(mappedBy="id", cascade=CascadeType.ALL)
    public List<Site> sites;

    public User(String firstName, String lastName, String email, String password) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
        this.password = password;
    }

    public static User connect(String email, String password) {
        return User.find("byEmailAndPassword",email,Crypto.passwordHash(password)).first();
    }

    public static User findUser(String email) {
        return User.find("byEmail",email).first();
    }

    public static User createUser(String firstName, String lastName, String email, String password, boolean isAdmin) {
        String pw = Crypto.passwordHash(password);

        User u = new User(firstName, lastName, email, pw);
        u.isAdmin = isAdmin;
        u.save();
        return u;
    }
}

@Entity
public class Site extends Model {

    public UUID siteId;

    public String alias;
    public String protocol;
    public String host;
    public String username;
    public String password;
    public int port;
    public String rootPath;

    @Lob
    public String description;

    @ManyToOne
    public User user;

    public Site(User user, String alias, String protocol, String host, String username, String password) {
        this.user = user;
        this.alias = alias;
        this.protocol = protocol;
        this.host = host;
        this.username = username;
        this.password = password;
        this.port = 21;
        this.siteId = UUID.randomUUID();

    }
}

When i try to run the following test:

当我尝试运行以下测试时:

public class BasicTest extends UnitTest {

    @Before
    public void setup() {
        Fixtures.deleteAll();
    }

    @Test
    public void createAndRetrieveUser() {
        new User("Jason","Miesionczek","something","something").save();
        User jason = User.find("byEmail", "something").first();

        assertNotNull(jason);
        assertEquals("Jason", jason.firstName);
    }

    @Test
    public void userSite() {
        new User("Jason","Miesionczek","something","something").save();
        User jason = User.find("byEmail", "something").first();

        new Site(jason, "InterEditor","ftp","something","something","something").save();

        List<Site> sites = Site.find("byUser", jason).fetch();

        assertEquals(1, sites.size());

        Site site1 = sites.get(0);
        assertNotNull(site1);
        assertEquals("InterEditor", site1.alias);
        assertNotNull(site1.siteId);
    }



}

And i get this error:

我得到这个错误:

A javax.persistence.PersistenceException has been caught, org.hibernate.exception.ConstraintViolationException: could not insert: [models.Site]
In /test/BasicTest.java, line 27 :
new Site(jason, "InterEditor","ftp","something","something","something").save();

Log output:

日志输出:

00:06:26,184 WARN  ~ SQL Error: -177, SQLState: 23000
00:06:26,184 ERROR ~ Integrity constraint violation - no parent FK2753674FD92E0A
 table: USER in statement [insert into Site (id, alias, description, host, passw
ord, port, protocol, rootPath, siteId, user_id, username) values (null, ?, ?, ?,
 ?, ?, ?, ?, ?, ?, ?)]

Can anyone help me understand what the error means and what i am doing wrong?

谁能帮助我理解错误的含义以及我做错了什么?

回答by Codemwnci

Your problem here is the mapping between the Site model class and the User model class. The error given is a missing foreign key.

您的问题是 Site 模型类和 User 模型类之间的映射。给出的错误是缺少外键。

If you comment out the Site list in your User class, your test will pass. So that has narrowed down the problem.

如果您在 User 类中注释掉 Site 列表,则您的测试将通过。这样就缩小了问题的范围。

Update:

更新:

The problem is because when your Site object is saved, it will save the child objects first (which includes the User object). When this happens, it is trying to create a reference to the Site object (due to the mappedBy parameter), but this has not been saved yet (this will be done AFTER the User object is saved).

问题是因为在保存 Site 对象时,它会首先保存子对象(包括 User 对象)。发生这种情况时,它会尝试创建对 Site 对象的引用(由于 mappingBy 参数),但这尚未保存(这将在保存 User 对象后完成)。

So, an alternative would be to map by a value you do have access to (such as the siteId), or add the User to the Site after it has been saved (so the ID value has been generated.

因此,另一种方法是按您有权访问的值(例如 siteId)进行映射,或者在保存用户后将其添加到站点(因此已生成 ID 值。

I changed your code to be mappedBy="siteId"and the test run fine.

我将您的代码更改为mappedBy="siteId"并且测试运行良好。

回答by Alaa Murad

I solved such a problem by using "INITIALLY DEFERRED DEFERRABLE" in Oracle, this delays the checking until you commit the whole transaction !

我通过在 Oracle 中使用“INITIALLY DEFERRED DEFERRABLE”解决了这个问题,这会延迟检查,直到您提交整个事务!