Hibernate Zero to One单向,具有反向主外键级联

时间:2017-06-23 09:25:45

标签: java mysql spring hibernate jpa

我在Spring Boot中遇到Hibernate的问题。

我们有2个表,usersuser_info,其中包含Zero To One(可以为一个可以为空的一对一)关系。 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
)

这些是模特:

@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;

    ...
}

当我使用此配置运行Spring应用程序时,它会抛出错误说:

org.hibernate.id.IdentifierGenerationException ids for this class must be manually assigned before calling save()

如果不是来自User实体的null,我们如何级联持久化UserInfo实例?

感谢您的回答!

1 个答案:

答案 0 :(得分:1)

您的映射是倒退的。 UserInfo应该引用它所附加的用户,并且是该关联的所有者。而且你还应该说它的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;
    ...