Jpa OneToOne共享主键一半有效

时间:2019-03-12 06:37:01

标签: spring-boot jpa spring-data-jpa one-to-one

我有SpringBoot 2.1.3和Java 8应用程序。用JPA构建数据库我有3个表一对一的关系。假设这些表如下:

@Entity
@Data //lombok
@Table(name = "users")
public class User {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(name = "id")
  private Long id;

  @OneToOne(mappedBy = "user", cascade = CascadeType.ALL)
  private Address address;
}

然后:

@Entity
@Data
@Table(name = "address")
public class Address {
  @Id
  @Column(name = "id")
  private Long id;

  @OneToOne
  @MapsId
  private User user;
}

这是有效的..这是最好的方法(此示例取自文档)。

如果我启动该应用程序,那么将创建数据库,并且如果我尝试添加实体,则一切正常。创建的模型如下:

Thw two table with onetoone relationships

现在,我想将Country对象添加到我的地址Entities中(例如),并按如下所示修改了Entities:

@Entity
@Data
@Table(name = "address")
public class Address {
 @Id
 @Column(name = "id")
 private Long id;

 @OneToOne
 @MapsId
 private User user;

 @OneToOne
 @MapsId
 private Country country;
}

和国家实体:

@Entity
@Data 
@Table(name = "country")
public class Country {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(name = "id")
  private Long id;

  @OneToOne(mappedBy = "country", cascade = CascadeType.ALL)
  private Address address;
}

应用程序仍会启动,创建数据库并遵循以下模型:

final model

但是,如果我尝试按以下方式保存用户:

User user = new User();
Address address = new Address();
Country country = new Country();

user.setAddress(address);
address.setUser(user);

address.setCountry(country);
country.setAddress(address);

userRepository.save(user);

我得到了错误:

java.sql.SQLException: Field 'country_id' doesn't have a default value

无论如何,我解决了删除@MapsId并添加@JoinColumn的问题,但我想了解问题所在。

P.S .:我正在使用带有InnoDB方言的MySQL 5.7(在application.properties上设置)

谢谢

0 个答案:

没有答案