andrey pripisnov
andrey pripisnov

Reputation: 3

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}
   }

Upvotes: 0

Views: 4240

Answers (3)

Hello world
Hello world

Reputation: 33

Use JSON Include to only show the Id, instead excluding everything

@JsonIncludeProperties(value = {"id"})

Upvotes: 3

Bender
Bender

Reputation: 92

I wouldn't leave spaces in here @GeneratedValue(strategy = GenerationType.IDENTITY) --> @GeneratedValue(strategy=GenerationType.IDENTITY). You do need a controller and a service annotated with @Restcontroller and @Service you can then setup a @Repository and simply is "findByID" (the Repository does actually understand this without any further implementation). The ID could be bind to a @Pathvariable and retrieve the value from the URL /Project/{id} and you might do something like this for e.g.

@RequestMapping(method=RequestMethod.POST, path="project/{id}")
void addUser(@Pathvariable Long id) {
    ProjectService.delete(id);
}

Try this https://www.youtube.com/watch?v=QHjFVajYYHM pretty much the same as you're trying.

Upvotes: 0

Chris
Chris

Reputation: 5673

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

Upvotes: 3

Related Questions