[英]Hibernate Zero to One unidirectional with reverse primary foreign key cascade
I'm facing a problem with Hibernate in Spring Boot. 我在Spring Boot中遇到了Hibernate的问题。
We have 2 tables, users
and user_info
, with a Zero To One (so a nullable One To One) relation. 我们有2个表,
users
和user_info
,具有零对一(因此可以为空的一对一)关系。 The user_info
has a primary foreign key that points to users.user_id
: user_info
有一个指向users.user_id
的主外键:
CREATE TABLE `users` (
`user_id` bigint(20) NOT NULL AUTO_INCREMENT,
`username` varchar(45) NOT NULL,
...
PRIMARY KEY (`user_id`)
)
CREATE TABLE `users_info` (
`user_id` bigint(20) NOT NULL,
`name` varchar(45) NOT NULL,
`surname` varchar(45) NOT NULL,
`mail` varchar(45) DEFAULT NULL,
...
PRIMARY KEY (`user_id`),
KEY `fk_user_id_idx` (`user_id`),
CONSTRAINT `fk_user_id` FOREIGN KEY (`user_id`)
REFERENCES `users` (`user_id`)
ON DELETE NO ACTION ON UPDATE NO ACTION
)
And these are the models: 这些是模型:
@Entity
@Table(name = "users")
public class User implements UserDetails, Buildable<User.Builder> {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_id")
private Long id;
private String username;
@Nullable
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name="user_id")
@JsonUnwrapped
private UserInfo userInfo;
...
}
@Entity
@Table(name = "users_info")
public class UserInfo {
@Id
@Column(name = "user_id")
private Long id;
@Nullable
private String name;
@Nullable
private String surname;
...
}
When I run the Spring application with this configuration, it throws an error saying: 当我使用此配置运行Spring应用程序时,它会引发错误消息:
org.hibernate.id.IdentifierGenerationException ids for this class must be manually assigned before calling save()
How can we cascade-persist the UserInfo
instance if not null from the User entity? 如果User实体中的
UserInfo
实例不为null,我们如何级联持久化UserInfo
实例?
Thanks for the answer(s)! 感谢您的回答!
Your mapping is backwards. 您的映射是向后的。 UserInfo should reference the user it's attached to, and be the owner of the association.
UserInfo应该引用它所附属的用户,并且是该关联的所有者。 And you should also say that its ID is also a foreign key to the user.
您还应该说它的ID也是用户的外键。
@Entity
@Table(name = "users")
public class User implements UserDetails, Buildable<User.Builder> {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_id")
private Long id;
private String username;
@Nullable
@OneToOne(mappedBy="user", cascade = CascadeType.ALL)
@JsonUnwrapped
private UserInfo userInfo;
...
}
@Entity
@Table(name = "users_info")
public class UserInfo {
@Id
@Column(name = "user_id")
private Long id;
@Nullable
private String name;
@Nullable
private String surname;
@OneToOne
@MapsId
private User user;
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.