我的hibernate数据库连接出了问题。起初我发布了一些数据:
Objects.java:
@Entity
@Table (name = "objects", schema="genmeta")
public class Objects {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int o_id;
private String o_name;
private String o_desc;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(name = "genmeta.object_tg_assc", joinColumns = { @JoinColumn(name = "o_id") }, inverseJoinColumns = { @JoinColumn(name = "tg_id") })
private Set<TemplateGroup> templateGroups;
@Transient
private boolean templateGroupsLoaded = false;
/**
* Getters and Setters
*/
}
TemplateGroup.java:
public class TemplateGroup {
@Id
@Column(unique=true, nullable=false)
private int tg_id;
private String tg_name;
private String tg_desc;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "templateGroups")
private Set<Objects> objects;
/**
* Getters and Setters
*/
}
我的问题是,我以后如何从我的类Object获取数据?
这是我的第一次尝试: 代码示例:
public Set<TemplateGroup> loadTemplateGroups(Objects myObjects) {
Session session = factory.openSession();
Set<TemplateGroup> myTG = myObjects.getTemplateGroups();
session.close();
return myTG;
}
非常感谢。
祝你好运 的Björn
答案 0 :(得分:1)
抛出failed to lazily initialize a collection of role: db.hibernate.classes.Objects.templateGroups, could not initialize proxy - no Session
异常是因为您正在一个事务中检索Objects
实例并在另一个事务中调用getTemplateGroups()
(或在第一个事务提交之后)。您不应该打开另一个会话来获取模板组。
您需要执行以下操作:
Session session = factory.openSession();
Objects object = <Code to retrieve the Objects instance>
Set<TemplateGroup> templateGroups = object.getTemplateGroups();
templateGroups.size(); // as an example
session.close();