hibernate的延迟加载(lazy loading)是一种性能优化技术,通过在需要访问数据时才实际加载它们,而不是在初始加载时将所有相关数据全部加载。这种方式可以减少不必要的数据查询和内存开销,特别是在处理大型数据集和复杂的对象关系时。
延迟加载的实现
在hibernate中,延迟加载通常应用于集合及关联关系中,比如@onetomany、@manytoone、@manytomany等。通过指定加载策略,可以控制关联实体的加载时机。
示例代码
下面是一个完整的示例,展示如何在hibernate中使用延迟加载。
配置文件hibernate.cfg.xml
<!doctype hibernate-configuration public
"-//hibernate/hibernate configuration dtd 3.0//en"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 数据库连接配置 -->
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/your_database</property>
<property name="hibernate.connection.username">your_username</property>
<property name="hibernate.connection.password">your_password</property>
<!-- hibernate 属性配置 -->
<property name="hibernate.dialect">org.hibernate.dialect.mysqldialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 映射类配置 -->
<mapping class="com.example.domain.student"/>
<mapping class="com.example.domain.course"/>
</session-factory>
</hibernate-configuration>
hibernateutil 类
import org.hibernate.sessionfactory;
import org.hibernate.cfg.configuration;
public class hibernateutil {
private static final sessionfactory sessionfactory;
static {
try {
// 从配置文件创建sessionfactory
sessionfactory = new configuration().configure("hibernate.cfg.xml").buildsessionfactory();
} catch (throwable ex) {
// 记录启动失败的错误
system.err.println("initial sessionfactory creation failed." + ex);
throw new exceptionininitializererror(ex);
}
}
public static sessionfactory getsessionfactory() {
return sessionfactory;
}
}
实体类 student 和 course
student 类
package com.example.domain;
import javax.persistence.*;
import java.util.hashset;
import java.util.set;
@entity
public class student {
@id
@generatedvalue(strategy = generationtype.identity)
private long id;
private string name;
private int age;
@onetomany(mappedby = "student", fetch = fetchtype.lazy, cascade = cascadetype.all)
private set<course> courses = new hashset<>();
public student() {}
public student(string name, int age) {
this.name = name;
this.age = age;
}
// getters 和 setters
public long getid() {
return id;
}
public void setid(long id) {
this.id = id;
}
public string getname() {
return name;
}
public void setname(string name) {
this.name = name;
}
public int getage() {
return age;
}
public void setage(int age) {
this.age = age;
}
public set<course> getcourses() {
return courses;
}
public void setcourses(set<course> courses) {
this.courses = courses;
}
}
course 类
package com.example.domain;
import javax.persistence.*;
@entity
public class course {
@id
@generatedvalue(strategy = generationtype.identity)
private long id;
private string name;
@manytoone(fetch = fetchtype.lazy)
@joincolumn(name = "student_id")
private student student;
public course() {}
public course(string name, student student) {
this.name = name;
this.student = student;
}
// getters 和 setters
public long getid() {
return id;
}
public void setid(long id) {
this.id = id;
}
public string getname() {
return name;
}
public void setname(string name) {
this.name = name;
}
public student getstudent() {
return student;
}
public void setstudent(student student) {
this.student = student;
}
}
延迟加载示例代码
下面的示例展示了如何在并发环境中使用延迟加载。
import org.hibernate.hibernate;
import org.hibernate.session;
import org.hibernate.sessionfactory;
import org.hibernate.transaction;
public class hibernatelazyloadingexample {
public static void main(string[] args) {
// 获取sessionfactory
sessionfactory sessionfactory = hibernateutil.getsessionfactory();
// 插入示例数据
insertsampledata(sessionfactory);
// 示例: 在打开和关闭会话时访问延迟加载的集合
session session = null;
transaction transaction = null;
try {
session = sessionfactory.opensession();
transaction = session.begintransaction();
// 获取student对象
student student = session.get(student.class, 1l);
system.out.println("student: " + student.getname() + ", age: " + student.getage());
// 在会话关闭前访问延迟加载的集合
system.out.println("courses (before session close): " + student.getcourses().size());
// 显式初始化延迟加载的集合
hibernate.initialize(student.getcourses());
transaction.commit();
} catch (exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printstacktrace();
} finally {
if (session != null) {
session.close();
}
}
// 在会话关闭后访问延迟加载的集合
session = sessionfactory.opensession();
transaction = session.begintransaction();
try {
student student = session.get(student.class, 1l);
system.out.println("student: " + student.getname() + ", age: " + student.getage());
// 会话关闭后访问延迟加载的集合会引发 lazyinitializationexception
system.out.println("courses (after session close): " + student.getcourses().size());
transaction.commit();
} catch (exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printstacktrace();
} finally {
if (session != null) {
session.close();
}
}
// 关闭sessionfactory
sessionfactory.close();
}
private static void insertsampledata(sessionfactory sessionfactory) {
session session = sessionfactory.opensession();
transaction transaction = session.begintransaction();
try {
student student = new student("john doe", 20);
course course1 = new course("mathematics", student);
course course2 = new course("physics", student);
student.getcourses().add(course1);
student.getcourses().add(course2);
session.save(student);
transaction.commit();
} catch (exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printstacktrace();
} finally {
if (session != null) {
session.close();
}
}
}
}
详细解释
配置延迟加载:在实体类的关联字段上添加
fetch = fetchtype.lazy注解。@onetomany(mappedby = "student", fetch = fetchtype.lazy, cascade = cascadetype.all) private set<course> courses = new hashset<>();
示例场景:
- 在一个会话中获取student对象及其关联的course集合。
- 在会话关闭前访问延迟加载的集合会触发集合的初始化。
- 使用
hibernate.initialize方法显式地初始化延迟加载的集合。 - 会话关闭后访问延迟加载的集合会引发
lazyinitializationexception异常。
事务管理:在事务中进行数据操作,并在操作完成后提交事务。如果操作失败,则回滚事务以确保数据一致性。
总结
延迟加载是一种有效的性能优化技术,通过在需要访问数据时才实际加载它们,可以减少不必要的数据查询和内存开销。在hibernate中,通过fetch = fetchtype.lazy注解可以方便地实现延迟加载。理解并正确应用延迟加载,可以有效地提高应用的性能和资源利用率。
到此这篇关于hibernate的延迟加载的项目实践的文章就介绍到这了,更多相关hibernate 延迟加载内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论