¿ìËÙÒµÎñͨµÀ

ϵͳѧϰhibernateÖ®¶þ SessionÖÐloadºÍget - ±à³ÌÈëÃÅÍø

×÷Õß ØýÃû¼¼Êõ À´Ô´ NET±à³Ì ä¯ÀÀ ·¢²¼Ê±¼ä 2012-06-20

ϵͳѧϰhibernateÖ®¶þ SessionÖÐloadºÍget

ʱ¼ä:2011-01-27 blogjava apple0668

ÓÃhibernateµÄORM¿ò¼ÜÓÐÒ»¶Îʱ¼äÁË£¬ÏÖÔÚÀ´»Ø¹ËÒ»ÏÂSeesionÖеÄloadºÍget¡£

Ò»¡¢get²»Ö§³Ölazy£¬loadÖ§³Ölazy¡£

¶þ¡¢²ÉÓÃget¼ÓÔØÊý¾Ý£¬Èç¹ûûÓÐÆ¥ÅäµÄÊý¾Ý£¬·µ»Ønull£¬¶øloadÔòÅ׳öÒì³£¡£

getµÄÀý×Ó£º

1public void testGetMethod() { 2¡¡¡¡¡¡¡¡Session session = null; 3¡¡¡¡¡¡¡¡try { 4¡¡¡¡¡¡¡¡¡¡¡¡session = HibernateUtils.getSession(); 5¡¡¡¡¡¡¡¡¡¡¡¡session.beginTransaction(); 6 7¡¡¡¡¡¡¡¡¡¡¡¡//ÂíÉÏ·¢³ö²éѯsql£¬¼ÓÔØUser¶ÔÏó 8¡¡¡¡¡¡¡¡¡¡¡¡User user = (User)session.get(User.class, "402880d01b9bf210011b9bf2c2ff0002"); 9¡¡¡¡¡¡¡¡¡¡¡¡System.out.println("user.name=" + user.getName()); 10 11¡¡¡¡¡¡¡¡¡¡¡¡user.setName("ÕÅÈý"); 12¡¡¡¡¡¡¡¡¡¡¡¡session.getTransaction().commit(); 13¡¡¡¡¡¡¡¡}catch(Exception e) { 14¡¡¡¡¡¡¡¡¡¡¡¡e.printStackTrace(); 15¡¡¡¡¡¡¡¡¡¡¡¡session.getTransaction().rollback(); 16¡¡¡¡¡¡¡¡}finally { 17¡¡¡¡¡¡¡¡¡¡¡¡HibernateUtils.closeSession(session); 18¡¡¡¡¡¡¡¡} 19¡¡¡¡}

PS£ºÔÚÖ´ÐеÚ8ÐÐÓï¾äµÄʱºò£¬Èç¹ûÊý¾Ý¿âÓÐÏà¹ØµÄ¼Ç¼£¬ÔòÁ¢¿Ì·¢³ösqlÓï¾ä£¬¼´Ê¹ÊÇûÓеÚ9ÐÐÖÐuser.getName()·½·¨µ÷Óã¬Èç¹ûûÓÐÆ¥ÅäµÄ¼Ç¼Ôò·µ»ØÀ´Ò»¸önull¡£

load·½·¨Àý×Ó£º

1public void testLoadMethod() { 2¡¡¡¡¡¡¡¡Session session = null; 3¡¡¡¡¡¡¡¡try { 4¡¡¡¡¡¡¡¡¡¡¡¡session = HibernateUtils.getSession(); 5¡¡¡¡¡¡¡¡¡¡¡¡session.beginTransaction(); 6 7¡¡¡¡¡¡¡¡¡¡¡¡//²»»á·¢³ö²éѯsql£¬ÒòΪload·½·¨ÊµÏÖÁËlazy£¨ÀÁ¼ÓÔØ»òÑÓ³Ù¼ÓÔØ£© 8¡¡¡¡¡¡¡¡¡¡¡¡//ÑÓ³Ù¼ÓÔØ£ºÖ»ÓÐÕæÕýʹÓÃÕâ¸ö¶ÔÏóµÄʱºò£¬²Å¼ÓÔØ£¨·¢³ösqlÓï¾ä£© 9¡¡¡¡¡¡¡¡¡¡¡¡//hibernateÑÓ³Ù¼ÓÔØʵÏÖÔ­ÀíÊÇ´úÀí·½Ê½ 10¡¡¡¡¡¡¡¡¡¡¡¡User user = (User)session.load(User.class, "402880d01b9bf210011b9bf2b2ff0002"); 11¡¡¡¡¡¡¡¡¡¡¡¡System.out.println("user.name=" + user.getName()); 12¡¡¡¡¡¡¡¡¡¡¡¡user.setName("ÀîËÄ"); 13¡¡¡¡¡¡¡¡¡¡¡¡session.getTransaction().commit(); 14¡¡¡¡¡¡¡¡}catch(Exception e) { 15¡¡¡¡¡¡¡¡¡¡¡¡e.printStackTrace(); 16¡¡¡¡¡¡¡¡¡¡¡¡session.getTransaction().rollback(); 17¡¡¡¡¡¡¡¡}finally { 18¡¡¡¡¡¡¡¡¡¡¡¡HibernateUtils.closeSession(session); 19¡¡¡¡¡¡¡¡} 20¡¡¡¡}

PS£ºÔÚÖ´Ðе½10¾ä´úÂëµÄʱºò²¢Ã»ÓÐÁ¢¿Ì·¢³ösqlÓï¾ä£¬ÓÉÓÚloadʵÏÖÁËlazyÑÓ³Ù¼ÓÔØ£¬ÑÓ³Ù¼ÓÔØÖ»ÓÐÕæÕýʹÓøöÔÏóµÄʱºò²Å½øÐмÓÔØ£¬·¢³ösqlÓï¾ä£¬¹Ø¼üÊÇ11¾ä´úÂë¡£Èç¹ûload·½·¨ÀïÃæµÄidÔÚÊý¾Ý¿â±íÀïÃæûÓÐÏà¹ØµÄ£¬Ôò»á·¢³öObjectNotFoundExceptionÒì³£¡£

PSPS£º¿ÉÒÔͨ¹ýÉèÖöϵ㣬ÓÃdebugÀ´¸ú×ÙÏà¹Ø±äÁ¿¸ú¶ÔÏóµÄ¸Ä±ä£¬ÕâÑù¾Í¿ÉÒÔºÜÇåÎúÀí½âloadºÍgetÕâÁ½¸ö·½·¨¡£

ÁèÖڿƼ¼×¨ÒµÌṩ·þÎñÆ÷×âÓᢷþÎñÆ÷Íйܡ¢ÆóÒµÓʾ֡¢ÐéÄâÖ÷»úµÈ·þÎñ£¬¹«Ë¾ÍøÕ¾£ºhttp://www.lingzhong.cn ΪÁ˸ø¹ã´ó¿Í»§Á˽â¸ü¶àµÄ¼¼ÊõÐÅÏ¢£¬±¾¼¼ÊõÎÄÕÂÊÕ¼¯À´Ô´ÓÚÍøÂç,ÁèÖڿƼ¼×ðÖØÎÄÕÂ×÷ÕߵİæȨ£¬Èç¹ûÓÐÉæ¼°ÄãµÄ°æȨÓбØҪɾ³ýÄãµÄÎÄÕ£¬ÇëºÍÎÒÃÇÁªÏµ¡£ÒÔÉÏÐÅÏ¢ÓëÎÄÕÂÕýÎÄÊDz»¿É·Ö¸îµÄÒ»²¿·Ö,Èç¹ûÄúҪתÔر¾ÎÄÕÂ,Çë±£ÁôÒÔÉÏÐÅÏ¢£¬Ð»Ð»!

·ÖÏíµ½£º ¸ü¶à

Copyright ©1999-2011 ÏÃÃÅÁèÖڿƼ¼ÓÐÏÞ¹«Ë¾ ÏÃÃÅÓÅͨ»¥Áª¿Æ¼¼¿ª·¢ÓÐÏÞ¹«Ë¾ All rights reserved

µØÖ·(ADD)£ºÏÃÃÅÈí¼þÔ°¶þÆÚÍûº£Â·63ºÅ701E£¨¶«ÄÏÈÚͨÅÔ£© Óʱà(ZIP)£º361008

µç»°£º0592-5908028 ´«Õ棺0592-5908039 ×ÉѯÐÅÏ䣺web@lingzhong.cn ×ÉѯOICQ£º173723134

¡¶ÖлªÈËÃñ¹²ºÍ¹úÔöÖµµçÐÅÒµÎñ¾­ÓªÐí¿ÉÖ¤¡·ÃöB2-20100024  ICP±¸°¸:ÃöICP±¸05037997ºÅ