懒加载集合在需要时加载子对象,这用于提高性能。从 Hibernate 3.0 开始,懒加载集合默认是启用的。

要使用懒加载集合,可以在集合中可选地使用 lazy="true" 属性。它默认是 true,所以通常不需要特别设置。如果将其设置为 false,所有的子对象将在初始加载,这在处理大数据时会降低性能。

让我们看看使用 lazy="true" 属性的 Hibernate 映射文件。

<list name="answers" lazy="true">
    <key column="qid"/>
    <index column="type"/>
    <one-to-many class="cn.javatiku.Answer"/>
</list>

示例:使用懒加载的持久类

Question.java

package cn.javatiku;

import javax.persistence.*;
import java.util.List;

@Entity
@Table(name="question")
public class Question {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String qname;

    @OneToMany(mappedBy="question", cascade=CascadeType.ALL)
    @LazyCollection(LazyCollectionOption.TRUE)
    private List<Answer> answers;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getQname() {
        return qname;
    }

    public void setQname(String qname) {
        this.qname = qname;
    }

    public List<Answer> getAnswers() {
        return answers;
    }

    public void setAnswers(List<Answer> answers) {
        this.answers = answers;
    }
}

Answer.java

package cn.javatiku;

import javax.persistence.*;

@Entity
@Table(name="answer")
public class Answer {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String answername;
    private String postedBy;

    @ManyToOne
    @JoinColumn(name="qid")
    private Question question;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getAnswername() {
        return answername;
    }

    public void setAnswername(String answername) {
        this.answername = answername;
    }

    public String getPostedBy() {
        return postedBy;
    }

    public void setPostedBy(String postedBy) {
        this.postedBy = postedBy;
    }

    public Question getQuestion() {
        return question;
    }

    public void setQuestion(Question question) {
        this.question = question;
    }
}

配置文件

hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 5.3//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hbm2ddl.auto">update</property>
        <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
        <property name="connection.username">system</property>
        <property name="connection.password">jtp</property>
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <mapping class="cn.javatiku.Question"/>
        <mapping class="cn.javatiku.Answer"/>
    </session-factory>
</hibernate-configuration>

存储和获取数据的用户类

Store.java

package cn.javatiku;

import org.hibernate.*;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

import java.util.ArrayList;
import java.util.List;

public class Store {
    public static void main(String[] args) {
        StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
        Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();

        SessionFactory factory = meta.getSessionFactoryBuilder().build();
        Session session = factory.openSession();

        Transaction t = session.beginTransaction();

        Answer ans1 = new Answer();
        ans1.setAnswername("Java is a programming language");
        ans1.setPostedBy("Ravi Malik");

        Answer ans2 = new Answer();
        ans2.setAnswername("Java is a platform");
        ans2.setPostedBy("Sudhir Kumar");

        List<Answer> list = new ArrayList<Answer>();
        list.add(ans1);
        list.add(ans2);

        Question q1 = new Question();
        q1.setQname("What is Java?");
        q1.setAnswers(list);

        ans1.setQuestion(q1);
        ans2.setQuestion(q1);

        session.persist(q1);

        t.commit();
        session.close();
        System.out.println("success");
    }
}

Fetch.java

package cn.javatiku;

import java.util.Iterator;
import java.util.List;

import javax.persistence.TypedQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class Fetch {
    public static void main(String[] args) {
        StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
        Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();

        SessionFactory factory = meta.getSessionFactoryBuilder().build();
        Session session = factory.openSession();

        TypedQuery<Question> query = session.createQuery("from Question q");
        List<Question> list = query.getResultList();

        Iterator<Question> itr = list.iterator();
        while (itr.hasNext()) {
            Question q = itr.next();
            System.out.println("Question: " + q.getQname());

            List<Answer> answers = q.getAnswers();
            for (Answer a : answers) {
                System.out.println(a.getAnswername() + " - " + a.getPostedBy());
            }
        }

        session.close();
        System.out.println("success");
    }
}

输出

运行 Store.java 时输出:

success

运行 Fetch.java 时输出:

Question: What is Java?
Java is a programming language - Ravi Malik
Java is a platform - Sudhir Kumar
success

标签: Hibernate, Hibernate教程, Hibernate框架, Hibernate框架设计, Hibernate初级教程, Hibernate框架用法, Hibernate指南, Hibernate入门, Hibernate中级教程, Hibernate进阶教程, Hibernate高级教程, Hibernate下载