简体   繁体   中英

Spring boot JPA entity

I have an entity called Order which has a reference to an entity called project like below:

@Entity
@Table(name = "customer_order")
public class Order {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    @ManyToOne
    @JoinColumn(name = "project_id", nullable = false)
    private Project project;

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

    @Column(name = "created_at")
    @CreationTimestamp
    private Date createdAt;
}

And my repository is as below:

@Repository
public interface OrderRepository extends JpaRepository<Order, Long> {
}

When I call my rest get endpoint to get a list of all orders, in the response, I get a project object inside the main order object with all properties of the 'project' class as well. I dont want this. I need a lean order response object with just the project id that it references. I tried using the below annotation over the 'project' property in the Order class, but it completely got rid of project details.

@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)

I still need the id of the project that is associated. How do I do it?

I assume that your endpoint rerturns JSON.

In that case you would have to write your own Serializer.

  • For Gson this can be achieved by implementing JsonSerializer and register it as a type adapter
  • For ObjectMapper (Jackson) you would have to extend StdSerializer and add it as a serializer to the ObjectMapper or use the annotation @JsonSerialize(using = ItemSerializer.class) on the model 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