简体   繁体   中英

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

I have an entity class with a Long id field. As a default, this field gets serialized to response with a Spring Boot rest controller.

I am using Spring Data JPA

I donot want to serialize this field into my response. I tried using @Transient, but that won't work. I can create a DTO object, but just wanted to check if there is a better way of achieving this behaviour?

You should avoid returning entities in controller responses. 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 . But... if it still not problems to you just add @jsonIgnore on the id field.

Don't use Enity in your response. Use another DTO class with fields you want to use. And map all data from entity to DTO class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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