我需要您的帮助,因为我不明白怎么了,这很烦我 我通过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;
}
}
这是一个从用户到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对象,通过设置器将其链接并具有对象图。而且我无法保存图形。
我认为addForeignKeyConstraint可能是错误的,导致当我删除此约束时它起作用(这是可以理解的),但是我应该如何在表上保存带有约束的对象?
请帮助我理解我的错误。
答案 0 :(得分:0)
我遇到了同样的问题,很难理解原因。
解决我的问题的是在@JoinColumn
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "id", referencedColumnName = "user_id", nullable = false)
private UserProfileInfo userProfileInfo;
答案 1 :(得分:0)
我更改了liquibase迁移并在列上设置了约束:
['a']
['b']
['c']
['d']
['a', 'b']
['a', 'c']
['a', 'd']
['a', 'b', 'c']
['a', 'b', 'd']
['a', 'b', 'c', 'd']
此后一切正常,并保存我的对象图