ibatis获取数据插入mysql时的自增字段
RT,ibatis获取数据插入mysql时的自增字段id,id是没有任何意义的自增主键,xml代码见下面,然后我在java里面用dao调用:Integer id = resCollDao.addMetadata(mData);System.out.println(id);,然后得到的id值始终为1,但是控制台能看到已经select出来的数据,是说这样select出来的数据不能直接在java里接吗?
<insert id="addMetadata" parameterType="MetadataBean"
useGeneratedKeys="true" keyProperty="id">
insert into cfsdc_metadata(
language,
contacterName,
unit,
position,
telephone,
fax,
address,
city,
province,
zip,
country,
email,
workhour,
createdTime
) values (
#{language},
#{contacterName},
#{unit},
#{position},
#{telephone},
#{fax},
#{address},
#{city},
#{province},
#{zip},
#{country},
#{email},
#{workhour},
#{createdTime}
)
<selectKey resultType="int" keyProperty="id" >
select @@IDENTITY as id
</selectKey>
</insert>
12-11-05@18:42:14 DEBUG - ooo Connection Opened
12-11-05@18:42:14 DEBUG - ==> Executing: insert into cfsdc_metadata( language, contacterName, unit, position, telephone, fax, address, city, province, zip, country, email, workhour, createdTime ) values ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
12-11-05@18:42:14 DEBUG - ==> Parameters: null, null, null, null, null, null, null, null, null, null, null, null, null, null
12-11-05@18:42:14 DEBUG - ==> Executing: select @@IDENTITY as id
12-11-05@18:42:14 DEBUG - ==> Parameters:
12-11-05@18:42:14 DEBUG - <== Columns: id
12-11-05@18:42:14 DEBUG - <== Row: 15
12-11-05@18:42:14 DEBUG - xxx Connection Closed
1
------最佳解决方案-------------------- <selectKey resultType="int" keyProperty="id" > select @@IDENTITY as id </selectKey>
这段可以修改下,看你用的是什么数据库,如果是mysql的话,形式是:<selectKey keyProperty="roomBookId" resultClass="java.lang.Integer">
<![CDATA[
SELECT LAST_INSERT_ID() AS roomBookId
]]>
</selectKey>
如果是oracle、PG、MSSQL这些的话,要先对你要获取的列建立一个sequence,类似于:
CREATE SEQUENCE t_theme_theme_id_seq
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 1
CACHE 1;
ALTER TABLE t_theme_theme_id_seq
OWNER TO postgres;
然后在ibatis的插入语句里面写:
<selectKey resultClass="Integer" keyProperty="themeId">
SELECT
currval('t_theme_theme_id_seq') as themeId;
</selectKey>
楼主可以去百度下currval的用法,它有几