开发者

Hibernate good practice when detaching Objects

开发者 https://www.devze.com 2023-03-12 04:39 出处:网络
After I construct a hibernate query, my code goes as follows: @SuppressWarnings(\"unchecked\") List<SendCommands> list = query.list();

After I construct a hibernate query, my code goes as follows:

@SuppressWarnings("unchecked")
List<SendCommands> list = query.list();
session.evict( list );
if( list.isEmpty() ) 
   return null;
SendCommands dst = list.get(开发者_如何学运维 0 );
return dst;

What is the "good" practice for this example:

1) detaching (evicting) the entire result set, then returning the first object of that set, or

2) detaching (evicting) only the first object of the set:

@SuppressWarnings("unchecked")
List<SendCommands> list = query.list();
if ( list.isEmpty() ) 
    return null;
SendCommands dst = list.get( 0 );
session.evict( dst );
return dst;


You don't need to detach the objects. Hibernate entities are POJOs, and are not lost at the end of the transaction. When the session is closed, they become detached automatically. But you can still use then and access their data, unless the data is marked as lazy-loaded and has not been fetched while the entities were attached.

0

精彩评论

暂无评论...
验证码 换一张
取 消