mybatis mapper.xml获取insert后的自增ID问题
作者:JaneYork
这篇文章主要介绍了mybatis mapper.xml获取insert后的自增ID问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
mybatis mapper.xml获取insert后的自增ID
在MyBatis中,要获取执行INSERT操作后的自增ID,可以在mapper.xml文件中的对应<insert>标签中使用useGeneratedKeys属性和keyProperty属性。
以下是一个示例:
<insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
INSERT INTO users (username, email) VALUES (#{username}, #{email})
</insert>在这个例子中,假设users表有一个自增主键字段id。useGeneratedKeys设置为true表示我们希望获取数据库生成的键值,keyProperty设置为Java对象中的属性名,MyBatis会将生成的ID设置到这个属性中。
确保你的数据表设置了自增主键,并且你的实体类中有对应的属性。
例如:
public class User {
private Integer id;
private String username;
private String email;
// getters and setters
}在执行insertUser操作后,MyBatis会将生成的ID自动设置到传入的User对象的id属性中。
mybatis mapper.xml常用写法
resultMap写法
<resultMap id="BaseResultVoMap" type="*.*.*.Entity" >
<id column="id" property="id" jdbcType="VARCHAR" />
<result column="value" property="value" jdbcType="VARCHAR" />
<result column="date" property="date" jdbcType="DATE" />
<result column="time" property="time" jdbcType="TIMESTAMP" />
<result column="status" property="status" jdbcType="INTEGER" />
<result column="bool" property="bool" jdbcType="BOOLEAN" />
</resultMap>if 书写
<if test=' value != null and value!= ""'>
value = #{value}
</if>foreach 书写
<foreach collection="ids" item="item" open="(" separator=" , " close=")" index="index">
#{item}
</foreach>批量插入
<insert id="insert" parameterType="java.util.Map">
insert into table(id, value, date, time, status)
values
<foreach collection="list" item="entity" separator=",">
(
#{entity.id},
#{entity.value},
#{entity.date},
#{entity.time},
#{entity.status}
)
</foreach>
</insert>批量更新
<update id="batchUpdate" parameterType="java.util.List">
<foreach collection="lists" item="item" index="index" open="" close="" separator=";">
UPDATE table_name
<set>
create_time = #{item.createTime}
</set>
WHERE id = #{item.id}
</foreach>
</update>choose 书写
<choose>
<when test=' time != null and time == "1" '>
table_${time}
</when>
<otherwise>
table_${date}
</otherwise>
</choose>大于小于
| <= | <= |
| >= | >= |
sql 书写
<sql id="BaseColumn">
id, value, date, time, status
</sql>
<select id="selectByPidsAndQids" parameterType="java.util.Map" resultMap="BaseResultVoMap">
SELECT <include refid="BaseColumn"/>
FROM table
</select>resultType中接受Date数据类型
<select id="queryMaxDate" resultType="java.util.Date">
SELECT MAX(date) as maxDate from dual
</select>总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
