【发布时间】:2020-01-24 16:54:42
【问题描述】:
Spring Boot 版本2.1.6。
我有User 类:
@Data
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
Long userID;
String eMail;
public User()
{
}
}
还有一个LoginCredential 类:
@Data
@Entity
public class LoginCredential {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
Long userID;
String eMail;
String passwordHash;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "id", referencedColumnName = "id")
User user;
public LoginCredential()
{
}
}
当我创建LoginCredential 的实例时,它不应该创建User 的实例吗?
因为我运行这个命令:curl -X POST -H "Content-Type: application/json" -d "{ \"email\": \"a\", \"passwordHash\": \"b\" }" http://localhost:8080/login
我得到了LoginCredential 的实例但没有User。
回应:
{"userID":1,"passwordHash":"b","user":null,"email":"a"}
然后我运行这个命令:curl -X POST -H "Content-Type: application/json" -d "{ \"email\": \"c\", \"passwordHash\": \"d\" ,\"user\":{}}" http://localhost:8080/login
而我得到的是什么都没有,不是同一个 ID。
回应:
{"userID":2,"passwordHash":"d","user":{"userID":3,"email":null},"email":"c"}
我错过了什么吗?如何解决?
LoginCredentialController 部分:
@PostMapping("/login")
LoginCredential newLoginCredential(@RequestBody LoginCredential newLoginCredential)
{
return repository.save(newLoginCredential);
}
我的pom.xml
【问题讨论】:
-
发布您的 curl 请求响应
-
你问过
Shouldn't it create an instance of User when I create an instance of LoginCredential?这取决于你在 /login 控制器方法上做了什么。也请在此处发布。 -
已编辑,请参阅@rimonmostafiz
-
两个结果都完全符合预期 - 第一个请求不包含
User所以你没有收到,第二个请求包含一个空的User所以你得到一个,但请考虑这个事实LoginCredential#userID与User#userID无关。 -
@Smutje 请参阅this,我设置了起点。看到他使用了**创建具有相同父母身份的孩子**的东西。我从 git 和教程中尝试了他的代码。不起作用。而且他的 tut 甚至与 git 代码都不匹配。
标签: spring hibernate spring-boot spring-data-jpa foreign-keys