關係,我在休眠以下層次:無法獲取的對象集合中的許多一對多從數據庫
@Entity
@Table(name = "elements")
@Inheritance(strategy=InheritanceType.JOINED)
public abstract class Elements implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "idelement")
private Integer idElement;
@ManyToMany(cascade = CascadeType.PERSIST, mappedBy = "elementsCollection")
private Collection<ElementsGroups> elementsGroupsCollection;
.
.
More attributes, constructor and getter/setter
.
.
}
@Entity
@Table(name = "valves")
@PrimaryKeyJoinColumn(name="idelement")
@XmlRootElement
public class Valves extends Elements {
@Basic(optional = false)
@Column(name = "position")
private int position;
@Basic(optional = false)
@Column(name = "status")
private boolean status;
.
.
More attributes, constructor and getter/setter
.
.
}
@Entity
@Table(name = "elementsgroups")
@XmlRootElement
public class ElementsGroups implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "idgroup")
private Integer idGroup;
@Basic(optional = false)
@Column(name = "description")
private String description;
@ManyToMany(cascade = {CascadeType.PERSIST})
@JoinTable(name="joinelementsgroups", joinColumns={@JoinColumn(name="idgroup")}, inverseJoinColumns={@JoinColumn(name="idelement")})
private Collection<Elements> elementsCollection;
.
.
More attributes, constructor and getter/setter
.
.
}
的想法是有一個「元素」超包裹的一堆元素該系統共享一些特徵和功能。這些元素可以分成幾組。這是數據庫結構:
當我堅持了Valve
子類的對象,並將其添加到一個組,我可以看到在數據庫中的變化。事情是這樣的:
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session s = sf.openSession();
Transaction tx = s.beginTransaction();
Valve v1 = new Valve();
Valve v2 = new Valve();
s.save(v1);
s.save(v2);
tx.commit();
tx = s.beginTransaction();
LinkedList<Elements> valves = new LinkedList<>();
valves.add(v1);
valves.add(v2);
ge.setElementsCollection(valves);
s.save(ge);
tx.commit();
//Database: OK
當我拿到Valve
對象,我可以得到該對象所屬的組,通過它的getter方法。當我試圖讓ElementsGroups
對象,在那裏我可以得到它的所有屬性出現問題,但elementsCollection
是不是含有Valve
前加入空:
tx = s.beginTransaction();
Valve v1 = (Valve)s.get(Valve.class, 3);
for(ElementsGroups g : v1.getElementsGroupsCollection())
System.out.println("Valve belongs to: " + g);
ElementsGroups ge = (ElementsGroups)s.get(ElementsGroups.class, 1);
System.out.println("Group number of elements: " + ge.getElementsCollection().size());
tx.commit();
輸出:
Valve belongs to: model.ElementsGroups[ idgroup=1 ]
Group number of elements: 0
我有已經實現的類似的關係不會顯示這個問題,所以我猜這個問題可能與類的層次結構有關,但我是Hibernate的新手,不知道我是否錯過了某些東西。
PS:請注意,我DROP掉的代碼的幾個部分,以方便其閱讀,但我可以添加必要時
ge.setElementsCollection(valves); - ge從哪裏來?它似乎是在交易之外創建的? –
對不起@MaciejKowalski,它在交易內部,我已經編輯了這部分代碼 – Juan