用户实体:
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int userId;
private String firstName;
private String lastName;
private String emailId;
private String phoneNumber;
@OneToMany(mappedBy="user", cascade= CascadeType.ALL, orphanRemoval = true)
private Set<Address> Addresses = new HashSet<Address>();
地址实体:
@Entity
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int addressId;
private String streetName;
private String houseNumber;
private String pinCode;
private String district;
private String state;
@ManyToOne(fetch = FetchType.LAZY, cascade= CascadeType.ALL)
@JoinColumn(name="userId")
@JsonIgnore
private User user = new User();
控制器类:
@RestController
public class UserController {
@Autowired
IUserService iUserService;
@RequestMapping(path = "/update")
public User updateCustomer(@RequestBody User user) {
return iUserService.save(user);
}
}
当我调用updateCustomer
方法时,存储了错误的数据。插入的值在下面给出,
SELECT * FROM ADDRESS ;
ADDRESS_ID DISTRICT HOUSE_NUMBER PIN_CODE STATE STREET_NAME USER_ID
1 kalaburgi 287 585105 karnataka jyanagar 2
2 bangalore 1387 560062 karnataka anjanpura 3
(2 rows, 1 ms)
SELECT * FROM USER;
USER_ID EMAIL_ID FIRST_NAME LAST_NAME PHONE_NUMBER
1 [email protected] sharan gilke 9900669988
2 null null null null
3 null null null null
[能否请您解释为什么为user
表存储了错误的数据。
来自邮递员的输入数据是:
{
"firstName" : "sharan",
"lastName" : "gilke",
"emailId" : "[email protected]",
"phoneNumber" : "9900669988",
"addresses" : [{
"streetName" : "jyanagar",
"houseNumber" : "287",
"pinCode" : "585105",
"district" : "kalaburgi",
"state" : "karnataka"
},
{
"streetName" : "anjanpura",
"houseNumber" : "1387",
"pinCode" : "560062",
"district" : "bangalore",
"state" : "karnataka"
}
]
}
因为您为每个User
创建了一个新的空白Address
:
private User user = new User();
这基本上是与JPA @OneToMany : foreign key is null相同的错误