当我执行以下代码时:
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 );
我获取了正确的resultSet:加载了所有消息,并加载了一些SendCommands,使得msg.getCommands()
不会发出额外的SQL查询。因此,我需要的所有信息都已被提取并正确映射。
但是,我遇到以下代码的问题:
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设法生成正确的SQL代码:
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
问题在于,当我尝试使用msg.getCommands()
时,Hibernate会发出一个新的SQL查询并获取与给定Message关联的sendCommands。有没有办法修复映射,或者有实际的Eager Fetch?