Hibernate (9) Lazy loading problem solving solution

Source: Internet
Author: User
Tags commit getmessage rollback
0 Lazy Load Concept

① lazy Load (load on demand) is a unique and powerful method of data acquisition, which means that the program defers access to the database, which ensures that sometimes unnecessary access to the database, because access to the database is time-consuming.
② when we query an object, by default, only the normal properties of the object are returned, and when the user goes to use the object property , the query is issued again to the database, a phenomenon known as lazy loading. 1 Configure off lazy load mode in Student.hbm.xml:

<class name= "com.test.domain.Student" table= "Student" lazy= "false" Schema= "SCOTT" >
2 hibernate.initialize (proxy object)

Displays the initialization proxy object Hibernate.initialize ((New Student ())). Getstudcourses ()); 3 openinview-is implemented by filters Filter Filter

principle:

The disadvantage is: Session closure will delay
Filter File , you do not need to configure the filter in Web. xml

public class Myfilter extends HttpServlet implements Filter {@Override public void Dofi
        Lter (ServletRequest arg0, Servletresponse arg1, Filterchain arg2) throws IOException, Servletexception {
        Session session = NULL;
        Transaction ts = null;
            try {session = Hibernateutil.getcurrentsession ();
            ts = session.begintransaction ();
            The entire request is completed before the DoFilter method is executed Arg2.dofilter (arg0, arg1);
        Ts.commit ();
            } catch (Exception e) {if (ts!=null) {ts.rollback ();
            } e.printstacktrace ();
        throw new RuntimeException (E.getmessage ());
        } finally {hibernateutil.closecurrentsession (); }} @Override public void init (Filterconfig arg0) throws Servletexception {//TODO auto-generated Me Thod stub}} 

Hibernateutil Tool class file
using the filter on the top of the mate with the openinview suffix

Public final class Hibernateutil {private static sessionfactory sessionfactory = null;
    Thread local mode private static threadlocal<session> threadloacal = new threadlocal<session> ();
    Private Hibernateutil () {} static {sessionfactory = new Configuration (). Configure (). Buildsessionfactory ();
    }//Get the new session public static session Opensession () {return sessionfactory.opensession ();
        }//Get and thread-associated session public static session Getcurrentsession () {Session session = Threadloacal.get ();
            Determine whether to get if (session==null) {session = Sessionfactory.opensession ();
        Place session into Threadlocal Threadloacal.set (session);
    } return session;
        } public static void Closecurrentsession () {Session session = Getcurrentsession ();
            if (Session!=null && session.isopen ()) {session.close ();
        Threadloacal.set (NULL);
}    }//method of returning objects by ID public static object FindByID (Class clazz, java.io.Serializable id) {Session sessio
        n = null;
        Transaction ts = null;
        Object obj = null;
            try {session = Opensession ();

            ts = session.begintransaction ();

            obj = Session.load (clazz, id);
        Ts.commit ();
            } catch (Exception e) {if (ts!=null) {ts.rollback ();
            } e.printstacktrace ();
        throw new RuntimeException (E.getmessage ());
            } finally {if (Session!=null && session.isopen ()) {session.close ();
    }} return obj; }//method of returning objects by ID public static object Findbyidopeninview (Class clazz, java.io.Serializable id) {Session
        Session = Getcurrentsession ();
        Object obj = Session.load (clazz, id);
    return obj; }//returns at most one object public static object Uniquequery (String hql,String[] Paras) {session session = NULL;
        Object obj = null;

            try {session = Opensession ();

            Query query = session.createquery (HQL);
                    if (paras!=null && paras.length>0) {for (int i=0; i<paras.length; i++) {
                Query.setstring (i, paras[i]);

        }} obj = Query.uniqueresult ();
            } catch (Exception e) {e.printstacktrace ();
        throw new RuntimeException (E.getmessage ());
            } finally {if (Session!=null && session.isopen ()) {session.close ();
    }} return obj; }///Paging public static List Executequerybypage (String hql, string[] paras, int pageSize, int pagenow) {Se
        Ssion session = NULL;
        List List = null;

            try {session = Opensession ();

            Query query = session.createquery (HQL); if (paras!=null && paras.length>0) {for (int i=0; i<paras.length; i++) {QUERY.SETST
                Ring (I, paras[i]);

            }}///Query.setfirstresult ((pageNow-1) *pagesize). Setmaxresults (PageSize);

        List = Query.list ();
            } catch (Exception e) {e.printstacktrace ();
        throw new RuntimeException (E.getmessage ());
            } finally {if (Session!=null && session.isopen ()) {session.close ();
    }} return list; 
        }///Paging public static List Executequerybypageopeninview (String hql, string[] paras, int pageSize, int pagenow) {

        Session session = Getcurrentsession ();

        Query query = session.createquery (HQL); if (paras!=null && paras.length>0) {for (int i=0; i<paras.length; i++) {query.se
            Tstring (i, paras[i]); 
}
        }

        ///        Query.setfirstresult ((pageNow-1) *pagesize). Setmaxresults (PageSize);

        List List = Query.list ();
    return list;
        }///query interface public static List executeQuery (String hql, string[] Paras) {session session = NULL;
        List List = null;

            try {session = Opensession ();

            Query query = session.createquery (HQL);
                    if (paras!=null && paras.length>0) {for (int i=0; i<paras.length; i++) {
                Query.setstring (i, paras[i]);

        }} list = Query.list ();
            } catch (Exception e) {e.printstacktrace ();
        throw new RuntimeException (E.getmessage ());
            } finally {if (Session!=null && session.isopen ()) {session.close ();
    }} return list; }///query interface public static List Executequeryopeninview (String hql, string[] paras) {SessIon session = Getcurrentsession ();

        Query query = session.createquery (HQL); if (paras!=null && paras.length>0) {for (int i=0; i<paras.length; i++) {query.se
            Tstring (i, paras[i]);

        }} List List = Query.list ();
    return list;
        }///modify and delete bulk SQL public static void Executeupdate (String hql, string[] Paras) {session session = NULL;
        Transaction ts = null;
            try {session = Opensession ();
            ts = session.begintransaction ();

            Query query = session.createquery (HQL);
                    if (paras!=null && paras.length>0) {for (int i=0; i<paras.length; i++) {
                Query.setstring (i, paras[i]);

            }} query.executeupdate ();
        Ts.commit ();
            } catch (Exception e) {if (ts!=null) {ts.rollback (); } E.PRIntstacktrace ();
        throw new RuntimeException (E.getmessage ());
            } finally {if (Session!=null && session.isopen ()) {session.close ();
        }}}///modify and delete bulk SQL public static void Executeupdateopeninview (String hql, string[] paras) {

        Session session = Getcurrentsession ();

        Query query = session.createquery (HQL); if (paras!=null && paras.length>0) {for (int i=0; i<paras.length; i++) {query.se
            Tstring (i, paras[i]);
    }} query.executeupdate ();
        }//Add public static void Save (Object obj) {session session = NULL;
        Transaction ts = null;
            try {session = Opensession ();
            ts = session.begintransaction ();
            Session.save (obj);
        Ts.commit ();
            } catch (Exception e) {if (ts!=null) {ts.rollback ();
   }         E.printstacktrace ();
        throw new RuntimeException (E.getmessage ());
            } finally {if (Session!=null && session.isopen ()) {session.close (); }}}//Add public static void Saveopeninview (Object obj) {Session session = Getcurrentsessi
        On ();
    Session.save (obj);
 }
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.