开发者

Hibernate mapping issue with Criteria

When I execute the following code:

String sqlQuery = "SELECT {msg.*},  {cmd.*} " +
    "FROM schemaName.Messages AS msg " +
    "LEFT OUTER JOIN schemaName.send_commands AS cmd " +
    " ON cmd.message_key = msg.unique_key " +
    " AND ( cmd.priority = 1 ) " +
    "WHERE msg.sequence_received < 10";

Query query = session.createSQLQuery( sqlQuery )
          .addEntity( "msg",Messages.class )
          .addJoin( "cmd","msg.commands" )
          .addJoin( "msg", "cmd.message" );
query.setResultTransformer( Criteria.DISTINCT_ROOT_ENTITY );

I obtain the the correct resultSet: All the Messages are loaded, and some of the SendCommands are loaded, in such a manner that msg.getCommands() does NOT issue an extra SQL query. Thus all the information I need has been fetched and properly mapped.

However, I have an issue with the following code:

Criteria crit = session.createCriteria( Messages.class )
     .add( Restrictions.lt( "sequenceReceived", Long.valueOf( 10 )) )
   开发者_运维问答  .setFetchMode( "commands", FetchMode.JOIN )
     .createAlias( "commands", "cmd", Criteria.LEFT_JOIN, Restrictions.eq( "cmd.priority", 1 ) )          
     .setResultTransformer( Criteria.DISTINCT_ROOT_ENTITY );

, hibernate manages to generate the correct SQL code:

SELECT  [...]
FROM schemaName.Messages AS msg LEFT OUTER JOIN schemaName.send_commands AS cmd  
ON cmd.message_key = msg.unique_key  AND ( cmd.priority = 1 ) 
WHERE msg.sequence_received < 10

The problem is that when I try to use msg.getCommands(), Hibernate issues a new SQL query and fetches the sendCommands associated with a given Message. Is there a way to fix the mapping, or to have an actual Eager Fetch?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜