SpringBoot JPA OneToMany返回空集合

时间:2019-06-25 15:02:59

标签: spring-data-jpa one-to-many

我正在学习SpringBoot JPA @OneToMany和@ManyToOne批注。现在,ManyToOne有效,但OneToMany不起作用,查询返回一个空集合。

这是两个实体的关系: (一个)DetectUnit包含(许多)设备

面对这个问题,我尝试在许多情况下更改@OneToMany属性,但仍然无法正常工作。

1. Device.java
//...
@ManyToOne(targetEntity=DetectUnit.class, fetch=FetchType.EAGER)
private DetectUnit detectUnit;
//...Getters, Setters


2. DetectUnit.java
//...
@OneToMany(targetEntity=Device.class, fetch=FetchType.EAGER) 
private List<Device> devices;
//...Getters, Setters

ManyToOne,工作正常,这是查询结果:

[ 
 ...
 {
        "id": 5,
        "no": "ML002",
        "name": "梅李镇2号机",
        "deployTime": "2015-01-12",
        "detectUnit": { //works
            "id": 2,
            "no": "002",
            "name": "梅李检测站",
            "devices": []
        }
  },
 ...
]

OneToMany,不起作用,这是查询结果:

[
    {
        "id": 1,
        "no": "001",
        "name": "碧溪检测站",
        "devices": [] //not work ,empty ?
    },
    {
        "id": 2,
        "no": "002",
        "name": "梅李检测站",
        "devices": [] //not work, empty ?
    }
]

有人遇到同样的问题吗?

1 个答案:

答案 0 :(得分:1)

当您具有诸如ManyToOne的关系时:

@ManyToOne(targetEntity=DetectUnit.class, fetch= FetchType.EAGER)
private DetectUnit detectUnit;

对于OneToMany,在DetectUnit中,指定“ mappedBy”:

@OneToMany(mappedBy = "detectUnit", fetch= FetchType.EAGER)
private List<Device> devices;

否则,它将创建第三个表以将两者关联。

相关问题