Mybatis简单使用——插入并返回主键(2)
1、Mybatis解决中文乱码和批量操作:
jdbc.url=jdbc:mysql://127.0.0.1:3306/mapper?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true
2、插入返回主键:
(1)支持主键自增( MySQL 和 SQL Server):
设值 useGeneratedKeys="true",指定目标属性keyProperty="id"
或者:
获取id:
批量插入:
<insert id="insertBatchContry" parameterType="java.util.List" useGeneratedKeys="true" keyProperty="id"> insert into country(countryname,countrycode,pmt)values <foreach item="item" collection="list" separator=","> (#{item.countryname},#{item.countrycode},#{item.pmt}) </foreach> </insert>
(2)不支持自动生成类型的数据库,插入获取主键(Oracle):
<insert id="addEmp" databaseId="oracle"> <selectKey keyProperty="id" order="BEFORE" resultType="Integer"> <!-- BEFORE--> select EMPLOYEES_SEQ.nextval from dual <!-- AFTER: select EMPLOYEES_SEQ.currval from dual --> </selectKey> <!-- 插入时的主键是从序列中拿到的 --> <!-- BEFORE:--> insert into employees(EMPLOYEE_ID,LAST_NAME,EMAIL) values(#{id},#{lastName},#{email}) <!-- AFTER: insert into employees(EMPLOYEE_ID,LAST_NAME,EMAIL) values(employees_seq.nextval,#{lastName},#{email}) --> </insert>