gpt4 book ai didi

java - Spring JPA Repository ony 在结果中获取 id 而不是完整对象

转载 作者:行者123 更新时间:2023-11-30 07:52:33 25 4
gpt4 key购买 nike

在 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 条消息,前两条消息发送给同一个用户,只有这两条消息中的第一 strip 有完整的用户对象,第二条只有它的 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
}

]

如果第 3 条消息来自非重复用户,则它带有完整对象。

我总是需要完整的对象。

而且-顺便说一句-在数据库中它们看起来都不错而且方式相同。

有什么想法吗?

提前谢谢大家!

最佳答案

由于您指定了注释 JsonIdentityInfo,Jackson 将对象序列化为生成的 JSON。

注释的 Javadoc 指定:

In practice this is done by serializing the first instance as full object and object identity, and other references to the object as reference values.

因此,如果您不希望出现这种行为,请删除注释。

关于java - Spring JPA Repository ony 在结果中获取 id 而不是完整对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45785037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com