我需要将2个表连接到一个具有某些条件的对象中。我有以下内容:
@Entity
@Table(name = "polling")
public class Polling extends DomainIdObject {
@ManyToOne
@JoinColumn(name = "owner_id")
private Person owner;
@Column(name = "poll_name")
private String name;
@Column(name = "description")
private String description;
@ManyToMany(targetEntity = PollingSchedule.class, mappedBy = "polling", fetch = FetchType.EAGER)
private List<PollingSchedule> variants;
@Column(name = "start_time")
private LocalDateTime startTime;
@Column(name = "end_time")
private LocalDateTime endTime;
//getters and setters
@Entity
@Table(name = "polling_schedule")
public class PollingSchedule extends DomainIdObject {
@JoinColumn(name = "polling_id")
private Polling polling;
@Column(name = "poll_var")
private String pollingVariant;
//gettters and setters
但是当我执行以下代码时:
Query query = getEntityManager().createNativeQuery("SELECT * FROM polling p WHERE p.id=1", Polling.class);
List list = query.getResultList();
List<PollingSchedule> variants = ((Polling) list.get(0)).getVariants();
变种列表为空。 DB中的表格如下:
polling
|id|owner_id|poll_name|description|start_time|end_time|
polling_schedule
|id|polling_id|poll_var|
因此,在结果中我希望Polling对象只包含那些PollingVariants,它们在polling_schedule表中有相应的polling_id。
我尝试使用Filter,SecondaryTable注释,但它对我不起作用(或者我使用它不正确)。
我使用hibernate4和spring boot 1.5.1
有人可以帮助我吗?
答案 0 :(得分:4)
我认为Polling
和PollingSchedule
之间的关系是一对多(不是多对多)。由于您需要在这些对象之间建立双向关系,因此您应该像这样更改它们:
Pooling.java
@Entity
@Table(name = "polling")
public class Polling extends DomainIdObject {
...
@OneToMany(mappedBy="polling")
private List<PollingSchedule> variants;
...
}
PoolingSchedule.java
@Entity
@Table(name = "polling_schedule")
public class PollingSchedule extends DomainIdObject {
@ManyToOne
@JoinColumn(name = "polling_id")
private Polling polling;
...
}