Spring Boot @ManyToOne only Id @JsonProperty

徘徊边缘 提交于 2021-01-29 09:00:21

问题


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

回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/60357405/spring-boot-manytoone-only-id-jsonproperty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!