Reputation: 686
I need to join 2 tables into one object with some condition. I have the following:
@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
but when I execute the following code:
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();
the variants list is empty. Tables in DB looks following:
polling
|id|owner_id|poll_name|description|start_time|end_time|
polling_schedule
|id|polling_id|poll_var|
So, in result I want that Polling object contains only those PollingVariants, that have corresponding polling_id in polling_schedule table.
I've try use Filter, SecondaryTable annotations, but it`s not work for me (or I was incorrect use it).
I use hibernate4 and spring boot 1.5.1
Could anyone help me?
Upvotes: 4
Views: 17889
Reputation: 526
I think the relation between Polling
and PollingSchedule
is one-to-many (not many-to-many). And since you need a bidirectional relationship between those objects, you should change them like this:
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;
...
}
Upvotes: 7