【发布时间】:2018-11-30 14:34:59
【问题描述】:
我需要你的帮助,因为我不明白出了什么问题,这让我很烦 我通过 liquibase 创建了两个具有一对一关系的表:
<changeSet id="create user_profile_info table" author="aarexer">
<createTable tableName="user_profile_info">
<column name="id" type="BIGINT" autoIncrement="true">
<constraints primaryKey="true" nullable="false"/>
</column>
<column name="user_id" type="BIGINT"/>
</createTable>
</changeSet>
<changeSet id="create users table" author="aarexer">
<createTable tableName="users">
<column name="id" type="BIGINT" autoIncrement="true">
<constraints primaryKey="true" nullable="false"/>
</column>
</createTable>
<addForeignKeyConstraint baseColumnNames="id"
baseTableName="users"
constraintName="fk_user_to_user_profile"
referencedColumnNames="user_id"
referencedTableName="user_profile_info"/>
</changeSet>
并用这种关系为它写java实体,这是UserProfileInfo:
@Data
@Entity
@Table(name = "user_profile_info")
public class UserProfileInfo implements Serializable {
@Id
@GenericGenerator(name = "native", strategy = "native")
@GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
private Long id;
public UserProfileInfo() {
}
public UserProfileInfo(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
这是User 实体:
@Data
@Entity
@Table(name = "users")
public class User implements Serializable {
@Id
@GenericGenerator(name = "native", strategy = "native")
@GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
private Long id;
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "id", referencedColumnName = "user_id")
private UserProfileInfo userProfileInfo;
// Hibernate requires a no-arg constructor
public User() {
}
public User(String firstName) {
this.firstName = firstName;
}
}
这是一个从 User 到 UserProfile 的定向链接。
乍一看还不错,但是当我尝试保存时:
UserProfileInfo entity = new UserProfileInfo("98518872");
User user = new User("Aleksandr");
user.setUserProfileInfo(entity);
userRepository.save(user);
我看到Referential integrity constraint violation 错误导致fk_user_to_user_profile。
怎么了?
我创建了 user 和 user_info 对象,通过 setter 链接它并拥有对象图。而且我无法保存我的图表。
我认为 addForeignKeyConstraint 可能有错误,因为当我删除此约束时它会起作用(这是可以理解的),但是我应该如何在表上保存带有约束的对象?
请帮助我理解我的错误。
【问题讨论】:
标签: hibernate spring-boot liquibase