春天:json没有表现出重复的OneToMany诱惑

时间:2017-06-30 22:05:40

标签: json spring hibernate

我已经花了半天时间而且没有找到答案。当我在Postman中发送GET请求以获取我的所有实体时,它不会给我重复的值。这是我的代码。

@Entity
@Table(name = "SERVICE")
public class Service {

    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    @JsonView(View.OnlyService.class)
    private Long id;

    @Column(name = "SERVICE_NAME", length = 50, unique = true)
    @NotNull
    @JsonView({View.OnlyService.class, View.OnlyCategory.class})
    private String serviceName;

    @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id", scope = ServerRequest.class)
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "CATEGORY_ID", referencedColumnName = "ID")
    @JsonView(View.OnlyService.class)
    private Category category;

    // getters and setters
}

@Entity
@Table(name = "CATEGORY")
public class Category {

    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy=GenerationType.AUTO)
    @JsonView(View.OnlyCategory.class)
    private int id;

    @Column(name = "NAME", length = 50)
    @NotNull
    @JsonView({View.OnlyService.class, View.OnlyCategory.class})
    @Enumerated(EnumType.STRING)
    private CategoryName name;

    @OneToMany(mappedBy="category", cascade=CascadeType.ALL, fetch = FetchType.LAZY)
    @JsonView(View.OnlyCategory.class)
    private List<Service> services;

    // getters and setters
}

@RestController
public class ServiceRestService {

    @Autowired
    ServiceRepository serviceRepository;
    @Autowired
    CategoryRepository categoryRepository;

    @JsonView(View.OnlyService.class)
    @RequestMapping(path = "/getAll", method = RequestMethod.GET)
    public Iterable<Service> getAllServices() {
        //return this.serviceRepository.findByCategoryId(1);
        return this.serviceRepository.findAll();
    }
}

这给了像这样的json

[
{
    "id": 1,
    "serviceName": "Jon's Pharmacy",
    "category": {
        "name": "PHARMACY"
    }
},
{
    "id": 2,
    "serviceName": "Adam's shop",
    "category": {
        "name": "SHOP"
    }
},
{
    "id": 3,
    "serviceName": "Judd's pharmacy",
    "category": 1
},
{
    "id": 4,
    "serviceName": "Adam's pharmacy",
    "category": 1
}
]

而不是

[
{
    "id": 1,
    "serviceName": "Jon's Pharmacy",
    "category": {
        "name": "PHARMACY"
    }
},
{
    "id": 2,
    "serviceName": "Adam's shop",
    "category": {
        "name": "SHOP"
    }
},
{
    "id": 3,
    "serviceName": "Judd's pharmacy",
    "category": {
        "name": "PHARMACY"
    }
},
{
    "id": 4,
    "serviceName": "Adam's pharmacy",
    "category": {
        "name": "PHARMACY"
    }
}
]

如何强行去做?

原谅我所有的错误 - 这是我的第一个问题:)

0 个答案:

没有答案