MyBatis 3 - Spring
我想插入项目列表,并且每个项目 ID 都必须从“TVA_UPSELLADMIN_CHANNEL_SEQ.nextVal”生成,但我收到 .xml 验证错误,您不能在“foreach”中子级“selectKey”。
<insert id="insertServiceMappings" parameterType="java.util.List">
INSERT
<foreach collection="list" item="channel" index="index" >
<selectKey keyProperty="id" resultType="long" order="BEFORE">
SELECT TVA_UPSELLADMIN_CHANNEL_SEQ.nextVal from dual
</selectKey>
into tva_upselladmin_channel (id,source_id, service_id, name) values (#{id}, #{channel.sourceId}, #{channel.serviceId}, #{channel.name})
</foreach>
</insert>
最佳答案
MyBatis 当前版本(或与此相关的任何人)不允许使用 <selectKey>
在 <forEach>
里面标签。它是否仅用于遍历列表。
<foreach>
的 MyBatis dtd 验证部分标签如下:
<!ELEMENT foreach (#PCDATA | include | trim | where | set | foreach | choose | if | bind)*>
<!ATTLIST foreach
collection CDATA #REQUIRED
item CDATA #IMPLIED
index CDATA #IMPLIED
open CDATA #IMPLIED
close CDATA #IMPLIED
separator CDATA #IMPLIED
>
因此,为了解决您的问题,您必须遍历列表并使用额外的 select
设置所有 ID。 XML 上的定义。就像:
<select id="nextvalKey" resultType="java.lang.Integer">
SELECT TVA_UPSELLADMIN_CHANNEL_SEQ.nextVal from dual
</select>
你的插入部分会是这样的:
<insert id="insertServiceMappings" parameterType="java.util.List">
<foreach collection="list" item="channel" index="index" >
INSERT INTO tva_upselladmin_channel (id,source_id, service_id, name)
VALUES ( #{id}, #{channel.sourceId}, #{channel.serviceId}, #{channel.name});
</foreach>
</insert>
不要忘记 ;
在插入命令之后,因为 ORACLE 不支持多值插入,例如insert ... values (1,'bla'), (2, 'ble'), (3, 'bli');
)
因此,第二部分是在您的实现中使用一种方法来为列表中的项目设置每个 ID。它会是这样的:
public void someMethodInsertList(List<SomeObject> list){
//normally I do an implementation that allows me to use
//sqlSessionTemplate from mybatis through an extended class
for ( SomeObject obj : list ){
obj.setId( getSqlSessionTemplate.selectOne( 'nextvalKey' ) );
}
getSqlSessionTemplate.insert( 'insertServiceMappings', list );
}
希望对你有帮助
关于java - mybatis 3 selectkey inside foreach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31748177/