简体   繁体   English

如何不序列化 Spring Boot @RestController 中的 @Id 字段?

[英]How to not serialize @Id field in Spring Boot @RestController?

I have an entity class with a Long id field.我有一个带有 Long id 字段的实体 class 。 As a default, this field gets serialized to response with a Spring Boot rest controller.默认情况下,该字段被序列化以响应 Spring 引导 rest controller。

I am using Spring Data JPA我正在使用 Spring 数据 JPA

I donot want to serialize this field into my response.我不想将此字段序列化到我的回复中。 I tried using @Transient, but that won't work.我尝试使用@Transient,但这不起作用。 I can create a DTO object, but just wanted to check if there is a better way of achieving this behaviour?我可以创建一个 DTO object,但只是想检查是否有更好的方法来实现这种行为?

You should avoid returning entities in controller responses.您应该避免在 controller 响应中返回实体。 It is not suitable for projection need, create coupling betwen your access layer with the view one and potential side effect like lazy loading caused by some anti patterns like open session in view .它不适合投影需要,在您的访问层与视图一之间创建耦合以及潜在的副作用,例如由一些反模式(如open session in view引起的延迟加载。 But... if it still not problems to you just add @jsonIgnore on the id field.但是...如果对您来说仍然没有问题,只需在id字段上添加@jsonIgnore

Don't use Enity in your response.不要在回复中使用 Enity。 Use another DTO class with fields you want to use.将另一个 DTO class 与您要使用的字段一起使用。 And map all data from entity to DTO class.以及 map 从实体到 DTO class 的所有数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM