我需要将2个表连接到一个具有某些条件的对象。我有以下几点:通过jpa加入一个java对象中的两个表
@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();
变种列表是空的。在数据库表看起来如下:
polling
|id|owner_id|poll_name|description|start_time|end_time|
polling_schedule
|id|polling_id|poll_var|
所以,结果我想要的投票对象仅包含那些PollingVariants,那些在polling_schedule表相应polling_id。
我试过使用Filter,SecondaryTable注解,但它不适合我(或者我错误地使用它)。
我使用hibernate4和spring引导1.5.1
任何人都可以帮助我吗?
你可以使用JPQL查询,而不是本机查询以避免在第三行丑陋的铸造。 – Deltharis