org.hibernate.LazyInitializationException
Student.javaorg.hibernate.LazyInitializationException,hibernate,spring-mvc,Hibernate,Spring Mvc,Student.java package Model; import java.util.Set; public class Student { private int studentID; private String name; private String city; private Set<Address> AddressList; private Set<Contact> ContactList; public Set<Contact> g
package Model;
import java.util.Set;
public class Student {
private int studentID;
private String name;
private String city;
private Set<Address> AddressList;
private Set<Contact> ContactList;
public Set<Contact> getContactList() {
return ContactList;
}
public void setContactList(Set<Contact> contactList) {
ContactList = contactList;
}
public Set<Address> getAddressList() {
return AddressList;
}
public void setAddressList(Set<Address> addressList) {
AddressList = addressList;
}
public int getStudentID() {
return studentID;
}
public void setStudentID(int studentID) {
this.studentID = studentID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
Contact.java
package Model;
public class Contact {
private int contactId;
private String mobileNo;
public int getContactId() {
return contactId;
}
public void setContactId(int contactId) {
this.contactId = contactId;
}
public String getMobileNo() {
return mobileNo;
}
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
}
Student.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Model.Student" table="Student">
<id name="studentID" type="int">
<column name="StudentID" />
<generator class="identity" />
</id>
<property name="name" type="java.lang.String"/>
<property name="city" type="java.lang.String"/>
<set name="AddressList">
<key column="studentID"/>
<one-to-many class="Model.Address"/>
</set>
<set name="ContactList">
<key column="studentID"/>
<one-to-many class="Model.Contact"/>
</set>
</class>
Address.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Model.Address" table="Address">
<id name="Aid" type="int">
<column name="Aid" />
<generator class="identity" />
</id>
<property name="fullAddress" type="java.lang.String"/>
</class>
Contact.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Model.Contact" table="Contact">
<id name="contactId" type="int">
<column name="contactId" />
<generator class="identity" />
</id>
<property name="mobileNo" type="java.lang.String"/>
</class>
主要方法
public static void main(String[] args)
{
Configuration cfg=new Configuration();
cfg.configure("hibernate.cfg.xml");
SchemaExport se=new SchemaExport(cfg);
se.setOutputFile("D:\\abc.sql");
se.create(true,true);//create(boolean script, boolean export)
System.out.println("------------------Saving of Student--------------------");
Student student =new Student();
student.setName("Yograj");
student.setCity("Nanded");
Set<Address> addressList=new HashSet<Address>();
Address address=new Address();
address.setFullAddress("Chikhali Nanded");
addressList.add(address);
address=null;
address=new Address();
address.setFullAddress("karvenagar Pune");
addressList.add(address);
student.setAddressList(addressList);
Set<Contact> contactList=new HashSet<Contact>();
Contact contact=new Contact();
contact.setMobileNo("9403330577");
contactList.add(contact);
contact=null;
contact=new Contact();
contact.setMobileNo("9890864805");
contactList.add(contact);
student.setContactList(contactList);
boolean result=new StudentServices().SaveStudent(student);
if(result)
{
System.out.println("------------------Save Student succ..--------------------");
}
else
{
System.out.println("------------------Saving failed--------------------");
}
System.out.println("------------------Student Details--------------------");
List<Student> studentList=new StudentServices().GetStudentlist();
for (Student stud : studentList) {
System.out.println("Name:"+stud.getName());
System.out.println("City:"+stud.getCity());
for (Address add : stud.getAddressList()) {
System.out.println("Full Address:"+add.getFullAddress());
}
for (Contact cont : stud.getContactList()) {
System.out.println("Full Address:"+cont.getMobileNo());
}
}
System.out.println("Execution over.");
}
publicstaticvoidmain(字符串[]args)
{
Configuration cfg=新配置();
configure(“hibernate.cfg.xml”);
SchemaExport se=新SchemaExport(cfg);
se.setOutputFile(“D:\\abc.sql”);
se.create(true,true);//create(布尔脚本,布尔导出)
System.out.println(“--------------学生保存-----------------”;
学生=新生();
学生名称(“Yograj”);
学生集城市(“Nanded”);
Set addressList=new HashSet();
地址=新地址();
地址:setFullAddress(“Chikhali Nanded”);
地址列表。添加(地址);
地址=空;
地址=新地址();
地址:setFullAddress(“karvenagar Pune”);
地址列表。添加(地址);
student.setAddressList(地址列表);
Set contactList=new HashSet();
触点=新触点();
联系人:setMobileNo(“9403330577”);
联系人列表。添加(联系人);
联系人=空;
触点=新触点();
联系方式:setMobileNo(“9890864805”);
联系人列表。添加(联系人);
student.setContactList(联系人列表);
布尔结果=new StudentServices().SaveStudent(student);
如果(结果)
{
System.out.println(“--------------保存学生成功…”);
}
其他的
{
System.out.println(“-----------------保存失败-----------------”;
}
System.out.println(“-----------------学生详细信息-----------------”;
List studentList=new StudentServices().GetStudentlist();
适用于(学生名单:学生名单){
System.out.println(“Name:+stud.getName());
System.out.println(“城市:+stud.getCity());
对于(地址添加:stud.getAddressList()){
System.out.println(“完整地址:+add.getFullAddress());
}
对于(联系人cont:stud.getContactList()){
System.out.println(“完整地址:+cont.getMobileNo());
}
}
System.out.println(“执行完毕”);
}
Java
package Service;
import java.util.List;
import javassist.runtime.Inner;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;
import org.hibernate.sql.JoinType;
import Model.Address;
import Model.Contact;
import Model.Student;
public class StudentServices {
public boolean SaveStudent(Student student) {
try {
Configuration cfg = new Configuration().configure();
SessionFactory sf = cfg.buildSessionFactory();
Session session = sf.openSession();
Transaction transaction = session.beginTransaction();
session.save(student);
for (Address add : student.getAddressList()) {
session.save(add);
}
for (Contact cont : student.getContactList()) {
session.save(cont);
}
transaction.commit();
session.close();
return true;
} catch (HibernateException e) {
return false;
}
}
public List<Student> GetStudentlist() {
try {
Configuration cfg = new Configuration().configure();
SessionFactory sf = cfg.buildSessionFactory();
Session session = sf.openSession();
Transaction transaction = session.beginTransaction();
Criteria criteria = session.createCriteria(Student.class, "Student")
.createAlias("Student.AddressList", "Address",JoinType.INNER_JOIN)
.createAlias("Student.ContactList", "Contact",JoinType.INNER_JOIN);
List<Student> studentList = criteria.list();
transaction.commit();
session.close();
return studentList;
} catch (HibernateException e) {
return null;
}
}
}
套餐服务;
导入java.util.List;
导入javassist.runtime.Inner;
导入org.hibernate.Criteria;
导入org.hibernate.hibernateeexception;
导入org.hibernate.Session;
导入org.hibernate.SessionFactory;
导入org.hibernate.Transaction;
导入org.hibernate.cfg.Configuration;
导入org.hibernate.criteria.Restrictions;
导入org.hibernate.sql.JoinType;
导入模型。地址;
导入模型。联系人;
导入模型。学生;
公共班级学生服务{
公共布尔存储学生(学生){
试一试{
配置cfg=新配置().configure();
SessionFactory sf=cfg.buildSessionFactory();
Session Session=sf.openSession();
事务=会话。beginTransaction();
保存(学生);
对于(地址添加:student.getAddressList()){
会话。保存(添加);
}
对于(联系人:student.getContactList()){
会话。保存(续);
}
commit();
session.close();
返回true;
}捕获(休眠异常e){
返回false;
}
}
公共列表GetStudentlist(){
试一试{
配置cfg=新配置().configure();
SessionFactory sf=cfg.buildSessionFactory();
Session Session=sf.openSession();
事务=会话。beginTransaction();
标准=session.createCriteria(Student.class,“Student”)
.createAlias(“Student.AddressList”、“Address”、JoinType.INNER\u JOIN)
.createAlias(“Student.ContactList”,“Contact”,JoinType.INNER\u JOIN);
List studentList=criteria.List();
commit();
session.close();
返回学生名单;
}捕获(休眠异常e){
返回null;
}
}
}
当我执行main方法时,hibernate将创建数据库和表。在所有表中,它将存储记录,但当我使用criteria API获取记录时,它会给我错误“org.hibernate.LazyInitializationException”。尝试访问student中的方法以初始化代理 尝试在服务方法中调用student.getAddress().getFullAddress(),以初始化代理 这样,您将避免延迟初始化异常
另一种方法是将eager fetching设置为true,但我宁愿先使用第一种方法。在您的案例中,student.addressList和
student.contactList
使用延迟加载。延迟加载意味着,这些值不会与studentList一起加载,只有在使用getAddressList()
和getContactList
访问它们时才会加载
延迟加载仅在会话仍处于打开状态时有效。如果在关闭会话后还未访问加载的组件,将抛出LazyInitializationException,如您的示例所示
您正在做的是:
student.getAddressList()访问地址列表
getAddressList()
和getContactList()
后关闭会话,然后它才能工作
顺便说一下,当您只读取GetStudentlist中的数据时,您不需要开始事务,并且
package Service;
import java.util.List;
import javassist.runtime.Inner;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;
import org.hibernate.sql.JoinType;
import Model.Address;
import Model.Contact;
import Model.Student;
public class StudentServices {
public boolean SaveStudent(Student student) {
try {
Configuration cfg = new Configuration().configure();
SessionFactory sf = cfg.buildSessionFactory();
Session session = sf.openSession();
Transaction transaction = session.beginTransaction();
session.save(student);
for (Address add : student.getAddressList()) {
session.save(add);
}
for (Contact cont : student.getContactList()) {
session.save(cont);
}
transaction.commit();
session.close();
return true;
} catch (HibernateException e) {
return false;
}
}
public List<Student> GetStudentlist() {
try {
Configuration cfg = new Configuration().configure();
SessionFactory sf = cfg.buildSessionFactory();
Session session = sf.openSession();
Transaction transaction = session.beginTransaction();
Criteria criteria = session.createCriteria(Student.class, "Student")
.createAlias("Student.AddressList", "Address",JoinType.INNER_JOIN)
.createAlias("Student.ContactList", "Contact",JoinType.INNER_JOIN);
List<Student> studentList = criteria.list();
transaction.commit();
session.close();
return studentList;
} catch (HibernateException e) {
return null;
}
}
}
//the following is necessary for lazy loading
SessionFactory sf = null;
// open and bind the session for this test thread.
Session s = null;
// Session holder
SessionHolder holder = null;
BeanFactory beanFactory = null;
protected void onSetUp() throws Exception {
System.out.println("On SetUP----");
sf = (SessionFactory) beanFactory.getBean("sessionFactory");
s = sf.openSession();
TransactionSynchronizationManager.bindResource(sf, new SessionHolder(s));
}
protected void onTearDown() throws Exception {
System.out.println("On onTearDown----");
// unbind and close the session.
holder = (SessionHolder) TransactionSynchronizationManager.getResource(sf);
s = holder.getSession();
s.flush();
TransactionSynchronizationManager.unbindResource(sf);
SessionFactoryUtils.closeSession(s);
// SessionFactoryUtils.releaseSession(s, sf);
// teardown code here
}