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>
答案 0 :(得分:1)
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
>
因此,为了解决您的问题,您必须遍历列表设置所有ID,并在XML上添加额外的select
定义。这就像是:
<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 );
}
希望有所帮助
答案 1 :(得分:1)
我找到另一种解决方案如下,它对我有用!
<insert id="insertServiceMappings" parameterType="java.util.List" useGeneratedKeys="true">
<selectKey keyProperty="id" resultType="java.lang.Long" order="BEFORE">
SELECT TVA_UPSELLADMIN_CHANNEL_SEQ.nextVal as id FROM DUAL
</selectKey>
INSERT INTO
tva_upselladmin_channel (id,source_id, service_id, name)
SELECT TVA_UPSELLADMIN_CHANNEL_SEQ.nextVal, A.* from (
<foreach collection="list" item="channel" index="index" separator="union all">
SELECT
#{channel.sourceId} as source_id,
#{channel.serviceId} as service_id,
#{channel.name}) as name
FROM DUAL
</foreach> ) A
</insert>