Search code examples
jsonspring-bootspring-data-jpaentitymany-to-one

Spring Boot @ManyToOne only Id @JsonProperty


help me find JSON property annotation who give me choose an entity property to JSON serialization. I need only one.

I code like that:

@Entity
@Table(name = "pages")
public class Page {
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   @Column(name = "id")
   private Long id;

   @Column(name = "name")
   private String name;

   @JsonIgnoreProperties(value = {"name", "description", "pages"}) // it's working, but I want to simplify, I need only project id property to JSON
   @ManyToOne(fetch = FetchType.EAGER)
   @JoinColumn(name = "project_id")
   private Project project;

   //getters and setters
} 

And project entity:

@Entity
@Table(name = "projects")
public class Project {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "project_id")
    private Long id;

    @Column(name = "project_name")
    private String name;

    @Column(name = "description")
    private String description;


    @OneToMany(targetEntity = Page.class, mappedBy = "project", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @OrderBy("id")
    private List<Page> pages = new ArrayList<>();
}

And JSON should be:

   {
        "id": 10,
        "name": "Name",
        "project": {"id":1}
   }

Solution

  • Instead of working with too many annotations you should create a DataTransferObject (DTO) instead.

    Within the DTO you define exactly what information should be exposed and map every entity object to a DTO. This is than returned to the frontend, not the entity itself.

    Here is a good tutorial on the topic: https://www.baeldung.com/entity-to-and-from-dto-for-a-java-spring-application