开发者

Hibernate good practice when detaching Objects

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜