[英]mybatis 3 selectkey inside foreach
MyBatis 3 - 春天
我想插入項目列表,並且每個項目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在其當前版本(或任何人)中不允許在<forEach>
標記內使用<selectKey>
。 它是否僅用於遍歷列表。
<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>
別忘了;
在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 );
}
希望能幫助到你
我找到了另一種解決方案,它對我有用!
<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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.