![](/img/trans.png)
[英]@RepositoryRestResource entity fields null during add new entity with curl POST
[英]Add new entity with relation using Spring's RepositoryRestResource
所以我有User
:
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String username;
private String password;
@OneToOne
private Email email;
//getters setters, constructors
}
我有Email
,它是:
@Entity
public class Email {
@Id
@GeneratedValue
private Integer id;
private String address;
//getters setters, constructors
}
它们都有自己的CrudRepository
,并用RepositoryRestResource
注释。
我的问题是: 如果我要同时创建新用户和新电子邮件以及与该用户的电子邮件关系,应向https://localhost:8443/users
提供哪个请求主体? 我试过了,但是它创建了一个新的用户,其中的电子邮件地址为null
:
{
"username" : "test",
"password" : "test",
"email" : {
"address" : "olol@lol.kek"
}
}
弄清楚了!
用户的外观如下:
@Entity
@NoArgsConstructor
@AllArgsConstructor
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Getter
@Setter
private Integer id;
@Getter
@Setter
private String username;
@Getter
@Setter
private String password;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "email_id")
@Getter
@Setter
private Email email;
}
电子邮件:
@Entity
@NoArgsConstructor
@AllArgsConstructor
public class Email {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Getter
@Setter
private Integer id;
@Getter
@Setter
private String address;
@OneToOne(mappedBy = "email")
@Getter
@Setter
private User user;
public Email(String address) {
this.address = address;
}
}
问题是您必须在两者上都添加@OneToOne
批注,并为从属实体提供诸如@JoinColumn
参数,为所有者提供mappedBy
批注。 另外,有必要为Email
添加带有String
参数的构造函数,以便可以在运行时调用它(我想实际上是“ id以外的所有”构造函数)。
然后我只是在POST请求中将此JSON发送到https:// localhost:8443 / users :
{
"username" : "test",
"password" : "test",
"email" : "lolkek@cheburek.com"
}
它会在数据库中创建新用户,并为该用户创建具有该地址的新电子邮件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.