【发布时间】:2017-08-20 17:37:06
【问题描述】:
在一个 SpringBoot rest 应用程序中,我有两个类如下:
用户.java 和 Message.java。
消息具有 -from- 字段(用户)和 -to- 类型(用户)。
所以我做了这样的:
在 User.java 中:
@Entity
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class,
property="id")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String firstName;
private String lastName;
private String email;
@JsonIgnore
@OneToMany(mappedBy = "to")
private List<Message> receivedMessages;
@OneToOne
@JoinColumn(name = "type")
private UserType type;
在 Message.java 中:
@Entity
public class Message {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Integer id;
@ManyToOne
@JoinColumn(name = "from_user_id")
private User from;
@ManyToOne
@JoinColumn(name = "to_user_id")
private User to;
private String subject;
private String message;
private Date sentTime;
private Date readTime;
private Integer replyTo;
(setters & getters, etc)
显然它有效! -但是-假设我有 3 条消息,其中前两条发送给同一个用户,只有这两条中的第一条带有完整的用户对象,第二条只有它的 id,如下所示:
[
{
"id": 16,
"from": {
"id": 1,
"firstName": "Ale",
"lastName": null,
"email": "axfeea@gmail.com",
"username": null,
"password": "123456",
"avatar": "https://..............jpg",
"type": null
},
"to": 1,
"subject": "sub",
"message": "hola",
"sentTime": null,
"readTime": null,
"replyTo": null
},
{
"id": 17,
"from": {
"id": 2,
"firstName": "Carlos",
"lastName": "Perez",
"email": "efefe@fefe.com",
"username": null,
"password": "fe",
"avatar": "https://..................jpg",
"type": null
},
"to": 1,
"subject": "sub1",
"message": "chau",
"sentTime": null,
"readTime": null,
"replyTo": null
},
{
"id": 18,
"from": 2,
"to": 1,
"subject": "efefae",
"message": "oooook",
"sentTime": 1503249653000,
"readTime": null,
"replyTo": null
}
]
如果第三条消息带有非重复用户,则它带有完整对象。
我需要完整的对象总是来。
而且 -btw- 在数据库中它们看起来都很好,而且方式相同。
有什么想法吗?
提前谢谢大家!
【问题讨论】:
-
你能分享你的整个实体类吗?还有你分享的json你是怎么得到的?
-
我认为这与急切的惰性获取有关。
-
@Imran 这是什么意思?我试图指定要渴望,但它仍然会发生
-
@AmerQarabsa 我编辑了帖子添加了更多代码。我使用邮递员得到的 Json。
-
JSON 序列化使用什么,如何配置?
标签: java spring spring-boot spring-data-jpa