Jpa映射,插入语句的顺序

时间:2014-12-02 07:36:37

标签: java hibernate jpa orm

有两个实体具有双向一对一的关系。用户实体 - 是所有者。两者共享User实体的相同主键: 所有者(父)实体:

class User{
    @Id
    @Column
    @TableGenerator(name = USER_GENERATOR_NAME)
    @GeneratedValue(generator = USER_GENERATOR_NAME, strategy = GenerationType.TABLE)
    private Integer id;

    @OneToOne(mappedBy = "user", cascade = {CascadeType.PERSIST})
    private UserSettings userSettings;

    public UserEntityBean(){
       this.userSettings = new UserSettings(this);
    }
}

依赖实体:

class UserSettings{
    @Id
    @Column(nullable = false)
    private Integer id;

    @OneToOne(optional = false, fetch = FetchType.LAZY, targetEntity = User.class)
    @JoinColumn(name = "user_id", nullable = false, updatable = false)
    @MapsId
    private User user;

    public UserSettings(final User user)
    {
        this.user = user;
    }
}

当我在事务中创建新用户并在其上调用persist时,我收到错误: 引发者:com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:无法添加或更新子行:外键约束失败(testbduser_settings,CONSTRAINT FK_SETTINGS_TO_USER FOREIGN KEY( USER_ID)参考usersUSER_ID)ON DELETE CASCADE)

在sql日志中我可以看到,首先执行sql insert into user_settings。但是外键需要引用users表中的现有记录。 问题是我可以更改插入顺序吗?

我可以要求JPA提供商插入第一个用户,然后才能插入其user_settings吗?

0 个答案:

没有答案