hibernate延迟加载以及no-session

延迟加载:延迟加载(lazy load懒加载)是当在真正需要数据时,才执行SQL语句进行查询,避免了无谓的性能开销。

 延迟加载分类:

 01.类级别的查询策略

 02.一对多和多对多关联的查询策略

 03.多对一关联的查询策略


类级别的查询策略

     1.类级别可选的检索策略包括立即检索延迟检索默认为延迟检索

1.1立即检索:立即加载检索方法指定的对象,立即发送SQL
1.2 延迟检索:延迟加载检索方法制定的对象.在使用具体的属性时,再进行加载,才发送SQL

 

   2.无论<class>元素的lazy属性是true还是falseSessionget()方法及Querylist()方法在类级别总是使用立即检索策略

 

   3.<class>元素的lazy属性为true或默认值,Sessionload()方法不会执行查询数据库表的SELECT语句,仅返回代理类对象的实例,该代理类实例有如下特征:

3.1 Hibernate在运行时采用CGLIB工具动态生成
3.2 Hibernate创建代理类实例时,仅初始化其OID属性
3.3在应用程序第一次访问代理类实例的非OID属性时,Hibernate会初始化代理类实例

    3.4注意:类级别检索策略仅适用于load()方法




(立即加载,延迟加载等)检索,通过set元素的lazy属性设置。

01.一对多或者多对多检索策略由lazyfetch共同确定

    Lazy:决定关联对象初始化时机

    Fetch:决定SQL语句构建形式

02.fetch取值

    Join:迫切左外连接

    Select:多条简单SQL(默认值)

    Subselect:子查询

03.fetchlazy组合

  解析:fetch=join lazy会被忽略,迫切左外连接的立即检索

 

        Fetch=”select” lazy=”false”  多条简单SQL立即检索

        Fetch=”select” lazy=”true”  多条语句延迟检索

        Fetch=”select” lazy=”extra”  多条语句及其懒惰检索

 

        Fetch=”subselect” lazy=”false”  子查询立即检索

        Fetch=”subselect” lazy=”true”  子查询延迟检索

        Fetch=”subselect” lazy=”extra”  子查询及其懒惰检索

Extra:极其懒惰,只有访问集合对象的属性时才会加载,访问集合本身的属性时(例如,集合大小,生成count),不会立即加载。

注意:querylist()会忽略映射文件配置的左外连接查询,此时lazy属性重新生效。





具体案例

首先我们用的hibernate.hbm.xml都是一个的 直接上传一个就ok. 连接数据库 对应哪个包下仔细看一下。

<?xml version='1.0' encoding='UTF-8'?>
<!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="myeclipse.connection.profile">JDBC for MySQL</property>

        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>

        <property name="connection.url">jdbc:mysql://localhost:3306/book</property>

        <property name="connection.username">root</property>

        <property name="connection.password"></property>

        <property name="hibernate.show_sql">true</property>

        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.format_sql">true</property>
        <!–生成特定数据库sql–>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <!–thread指定当前线程来跟踪管理–>
        <property name="current_session_context_class">thread</property>


        <mapping resource="Dog.xml"></mapping>

    </session-factory>
-->

    <session-factory>
        <property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
        <property name="connection.username">sll</property>
        <property name="connection.password">sll</property>
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>

<property name="current_session_context_class">thread</property>
        <property name="show_sql">true</property>

<property name="hbm2ddl.auto">update</property>
        <property name="connection.autocommit">true</property>
     <!--   <mapping resource="cn/happy/hibernate01/Cat.hbm.xml"/>
        <mapping resource="cn/happy/hibernate02/Dept.hbm.xml"/>-->
     <!--   <mapping resource="cn/happy/hibernate03hql/Emp.hbm.xml"/>
        <mapping resource="cn/happy/hibernate04pagelist/Emp.hbm.xml"/>
        <mapping resource="cn/happy/hibernate06mapping/Emp.hbm.xml"/>
        <mapping resource="cn/happy/hibernate06mapping/Dept.hbm.xml"/>

        <mapping resource="cn/happy/hibernate07onttomany/Emp.hbm.xml"/>
        <mapping resource="cn/happy/hibernate07onttomany/Dept.hbm.xml"/>
-->
       <!-- <mapping resource="cn/happy/hibernate08save/Emp.hbm.xml"/>
        <mapping resource="cn/happy/hibernate08save/Dept.hbm.xml"/>

      <mapping resource="cn/happy/hibernate09manytomany/Employee.hbm.xml"/>
        <mapping resource="cn/happy/hibernate09manytomany/Project.hbm.xml"/>
        <mapping resource="cn/happy/hibernate11lazyLoad/Student.hbm.xml"/>-->
   <!--   <mapping resource="cn/happy/hibernate11lazyLoad/Emp.hbm.xml"/>
        <mapping resource="cn/happy/hibernate11lazyLoad/Dept.hbm.xml"/>-->
        <!--no-session-->
      <!--  <mapping resource="cn/happy/hibernate12nosession/Emp.hbm.xml"/>
        <mapping resource="cn/happy/hibernate12nosession/Dept.hbm.xml"/>
-->
        <mapping resource="cn/happy/hibernate10opensessioninview/Student.hbm.xml"/>
        <mapping class="cn.happy.hibernate13zj.Dept"></mapping>
        <mapping class="cn.happy.hibernate14onetoone.Humen"></mapping>
        <mapping class="cn.happy.hibernate14onetoone.Card"></mapping>
    </session-factory>
</hibernate-configuration>


然后因为这个没有用到注解 所以我们需要小配置

首先我们看一下实体类。

package cn.happy.hibernate11lazyLoad;

import java.util.Date;

/**
 * Created by linlin on 2017/10/9.
 */
public class Student {
    private Integer stuno;
    private String stuname;
    private Integer stuage;
    private Date studate;

    public Integer getStuno() {
        return stuno;
    }

    public void setStuno(Integer stuno) {
        this.stuno = stuno;
    }

    public String getStuname() {
        return stuname;
    }

    public void setStuname(String stuname) {
        this.stuname = stuname;
    }

    public Integer getStuage() {
        return stuage;
    }

    public void setStuage(Integer stuage) {
        this.stuage = stuage;
    }

    public Date getStudate() {
        return studate;
    }

    public void setStudate(Date studate) {
        this.studate = studate;
    }
}


每个 案例也就那几步 

小配置 :

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="cn.happy.hibernate11lazyLoad">
    <class name="Student" table="StudentNew" schema="sll"  lazy="true">
        <id name="stuno" column="stuno">
           <generator class="native"></generator>
        </id>
        <property name="stuname" />
       <property name="stuage"/>
        <property name="studate"/>
    </class>
</hibernate-mapping>


测试类:

package cn.happy.test;


import cn.happy.hibernate11lazyLoad.Dept;
import cn.happy.hibernate11lazyLoad.Emp;
import cn.happy.hibernate11lazyLoad.Student;
import cn.happy.hibernate12nosession.biz.HibernateBiz;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Before;
import org.junit.Test;

import java.util.List;
import java.util.Set;

/**
 * Created by linlin on 2017/9/22.
 */
public class test1009 {
    Configuration cfg;
    Transaction tx;
    Session session;
    SessionFactory factory;

    @Before
    public void myBefore() {
        //创建配置对象
        cfg = new Configuration().configure("Hibernate.cfg.xml");
        //根据配置对象创建SessionFactory
        factory = cfg.buildSessionFactory();
        //根据SessionFactory创建Session
        session = factory.openSession();
        //在Session创建后开启事务
        tx = session.beginTransaction();
    }


    @Test
    public void testmanyToOne() {
        Dept dept = session.get(Dept.class, 14);
        Set<Emp> emps = dept.getEmps();
        emps.size();
    }

    @Test
    public void testmanyToOne0() {
        Student student = session.load(Student.class, 1);
    }



}



这里下面的方法是上面测试 

下面这个是实体类和小配置是上面的方法

package cn.happy.hibernate11lazyLoad;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by linlin on 2017/9/24.
 */
public class Dept {
    private Integer deptno;
    private String deptname;

   private Set<Emp> emps=new HashSet<Emp>();

    public Set<Emp> getEmps() {
        return emps;
    }

    public void setEmps(Set<Emp> emps) {
        this.emps = emps;
    }

    public Dept() {
    }

    public Integer getDeptno() {
        return deptno;
    }

    public void setDeptno(Integer deptno) {
        this.deptno = deptno;
    }

    public String getDeptname() {
        return deptname;
    }

    public void setDeptname(String deptname) {
        this.deptname = deptname;
    }
}


 

package cn.happy.hibernate11lazyLoad;

/**
 * Created by linlin on 2017/9/24.
 */
public class Emp {
    private Integer empno;
    private String ename;

   private Dept dept;

    public Dept getDept() {
        return dept;
    }

    public void setDept(Dept dept) {
        this.dept = dept;
    }

    public Integer getEmpno() {
        return empno;
    }

    public void setEmpno(Integer empno) {
        this.empno = empno;
    }

    public String getEname() {
        return ename;
    }

    public void setEname(String ename) {
        this.ename = ename;
    }
}


小配置:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="cn.happy.hibernate08save">
    <class name="cn.happy.hibernate11lazyLoad.Dept" table="Dept" schema="sll">
        <id name="deptno" column="deptno">
            <generator class="native"/>
        </id>
        <property name="deptname" column="deptname"/>
        <set name="emps" lazy="false" fetch="join">
            <key column="deptno"/>
            <one-to-many class="Emp"/>
        </set>
    </class>


</hibernate-mapping>

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="cn.happy.hibernate08save">
    <class name="cn.happy.hibernate11lazyLoad.Emp" table="Emp" schema="sll">
        <id name="empno" column="empno">
            <generator class="native"/>
        </id>
        <property name="ename" column="enmae"/>
        <many-to-one name="dept" column="deptno" class="Dept"></many-to-one>
    </class>


</hibernate-mapping>


上面是延迟加载的 案例

下面是no-session



biz:

package cn.happy.hibernate12nosession.biz;

import cn.happy.hibernate12nosession.Emp;
import cn.happy.hibernate12nosession.dao.HibernateDAO;
import cn.happy.hibernate12nosession.util.HibernateUtil;
import org.hibernate.Hibernate;
import org.hibernate.Transaction;

import java.io.Serializable;

/**
 * Created by linlin on 2017/10/9.
 */
public class HibernateBiz {

    HibernateDAO dao=new HibernateDAO();
    public Object get(Class clazz, Serializable id) {
        Transaction tx = HibernateUtil.currentSession().beginTransaction();
        Object obj= dao.get(clazz, id);
       /* Emp emp=(Emp)obj;
        emp.getEname();*/
       if(!Hibernate.isInitialized(obj)){
           Hibernate.initialize(obj);
       }
        System.out.println("==============================================");
        tx.commit();
        HibernateUtil.closeSession();
        return obj;
    }
}



dao:

package cn.happy.hibernate12nosession.dao;



import cn.happy.hibernate10opensessioninview.util.HibernateUtil;

import java.io.Serializable;

/**
 * Created by linlin on 2017/10/9.
 */
public class HibernateDAO {

    public Object get(Class clazz, Serializable id) {
Object result= HibernateUtil.getSession().load(clazz,id);
return result;

    }
}


util:

package cn.happy.hibernate12nosession.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * Created by linlin on 2017/10/6.
 */
public class HibernateUtil {
    //getCurrentSession()底层实现原理
    //ThreadLocal变量
    public static final ThreadLocal<Session> threadTL=new ThreadLocal<Session>();

    //我想直接调用一个方法,获取Session
    //定义一个sessionFactory对象
    private static SessionFactory factory;
    private static Configuration cfg;
    static{
        cfg=new Configuration().configure();
        factory=cfg.buildSessionFactory();
    }
    //提供一个静态方法
    public static Session currentSession(){
        Session session=threadTL.get();
        if(session==null){  //当前线程中没有session对象
            session=factory.openSession();
            threadTL.set(session);
        }
        return session;

    }
    //关闭session
    public static void closeSession(){
        //获取线程中的session
        Session session = threadTL.get();
        if (session!=null) {
            threadTL.set(null);
            session.close();
        }
    }

}

Dept  Emp和上面的一样的

测试类

package cn.happy.test;



import cn.happy.hibernate12nosession.Emp;
import cn.happy.hibernate12nosession.biz.HibernateBiz;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Before;
import org.junit.Test;

import java.util.Set;

/**
 * Created by linlin on 2017/9/22.
 */
public class test1009_01 {
    Configuration cfg;
    Transaction tx;
    Session session;
    SessionFactory factory;

    @Before
    public void myBefore() {
        //创建配置对象
        cfg = new Configuration().configure("Hibernate.cfg.xml");
        //根据配置对象创建SessionFactory
        factory = cfg.buildSessionFactory();
        //根据SessionFactory创建Session
        session = factory.openSession();
        //在Session创建后开启事务
        tx = session.beginTransaction();
    }



    //no-session
    @Test
    public void loadGetTest() {
        HibernateBiz biz = new HibernateBiz();
       Emp emp = (Emp) biz.get(Emp.class, 1);
        System.out.println(emp.getEname());
    }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值