【问题标题】:Spring JPA Repository ony fetches id instead of full object when it's already in resultSpring JPA Repository 仅在结果中获取 id 而不是完整对象
【发布时间】: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


【解决方案1】:

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

注解的Javadoc指定:

实际上,这是通过将第一个实例序列化为完整的对象和对象标识,并将对对象的其他引用作为引用值来完成的。

因此,如果您不想要这种行为,请删除注释。

【讨论】:

  • 非常感谢!解决了问题:)
猜你喜欢
  • 1970-01-01
  • 2015-06-29
  • 2021-05-26
  • 1970-01-01
  • 2019-08-21
  • 2022-11-12
  • 2021-06-11
  • 2021-09-13
相关资源
最近更新 更多