如何将@JsonView应用于常见字段

时间:2019-01-24 18:43:09

标签: java spring spring-mvc jackson spring-rest

我有两个具有双向一对多关系的实体“公司”和“产品”。 为了摆脱序列化期间的循环,我使用@JsonView。因为我需要同时显示公司和产品的链接。

但是问题是我在抽象实体中有共享字段,以免重复代码。 示例代码:

@RestController
@RequestMapping("/api/companies")
public class CompanyController {

    @JsonView({CompanyViews.class})
    @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody List<Company> getAll() {
        return service.getAll();
    }
}

@RestController
@RequestMapping("/api/products")
public class ProductController {

    @JsonView({ProductViews.class})
    @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody List<Product> getAll() {
        return service.getAll();
    }
}

@Entity
public class Company extends AbstractEntity {

    @OneToMany(mappedBy = "company", cascade = CascadeType.ALL)
    @JsonView({CompanyViews.class})
    private Set<Product> products;
}

@Entity
public class Product extends AbstractEntity {

    @ManyToOne
    @JsonView({ProductViews.class})
    @JoinColumn(name = "company_id", nullable = false)
    private Company company;
}

@MappedSuperclass
public abstract class AbstractEntity implements BaseEntity {

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

    @Column(nullable = false, unique = true)
    protected String name;

    // setter getter
}

public interface BaseEntity {
    Long getId();
    void setId(Long id);
    String getName();
    void setName(String name);
}

如果您不标记注释公用字段-它们将不会序列化,但是我需要。

而且我不知道该如何标记常规字段。因为如果我有一百个实体,那么对于通用字段,我将有太多标记的类。

告诉我最好的解决方案或替代解决方案。

0 个答案:

没有答案