springboot—在使用jpa的JavaSpringBoot中进行一对一Map的情况下,我得到的是空值

kiayqfof  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(387)

我有以下两个实体:

users:
public class User implements Serializable {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column
    private Long userId;
    @Column(nullable = false)
    private String userName;
    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "user")
    @JoinColumn(name="userId", referencedColumnName = "userId")
    private Address address;
}

Address:
public class Address {
    @Id @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long addressId;
    private String streetName;
    private Long userId;
    @OneToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "userId", referencedColumnName="userId", insertable = false, updatable = false, nullable = false)
    private User user;
}

我正在做userrepository.save(user);用户对象如下:

{
    "userName" : "test",
    "Address" : {
         "streetName" : "street"
    }
}

但是在地址表中,userid是空的,即使有一个forign-key关系在那里,当我得到用户实体地址是空的时候,任何人都可以告诉我我哪里出错了。
提前谢谢。

ktecyv1j

ktecyv1j1#

如果我把上面的代码改成这样:

User.java
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "addressId")
private Address address;

Address.java
@OneToOne(mappedBy = "user")
private User user;

效果不错。

相关问题