daybreaksnow's diary

私を私と呼びたい

[Hibernate]session.loadとgetの違い

Hibernate In Action 4.4.1

 

・存在しないエンティティを読み込んだ場合

load:例外が発生する

get:nullが返る

 

・プロキシが利用されるかどうか

load:Proxyクラスが返され、実際に利用されるタイミングでselectが走る

get:常に実体クラスが返る

 

-----

Category cat = (Category) session.load(Category.class, id);

System.out.println(cat.getClass()); 

System.out.println(cat.getName());

----

・loadの場合の出力結果

class inaction.cascade.Category_$$_javassist_0

Hibernate: select category0_.category_id as category1_5_0_, category0_.parent_category_id as parent2_5_0_, category0_.name as name5_0_, category0_.created_date as created4_5_0_ from public.category category0_ where category0_.category_id=?

parent

 
 

・getの場合の出力結果

Hibernate: select category0_.category_id as category1_21_0_, category0_.parent_category_id as parent2_21_0_, category0_.name as name21_0_, category0_.created_date as created4_21_0_ from public.category category0_ where category0_.category_id=?

class inaction.cascade.Category

parent

 
 
loadの場合はgetNameが呼ばれるまでselect文が発行されていないことが分かる。