mybatis定义sql语句标签之insert标签

这是非常核心的一个标签,CURD是mybatis的核心功能。
insert元素相对于select元素要简单很多,mybatis会在插入之后返回一个整数,表示插入成功后插入的条数。
真实项目中,使用最多的一个点要注意,在插入过程中返回一些自动主键。
因为这个主键,在同一个事务中,还有其它用。例如级联。

属性介绍

属性 说明
id 可以理解为Mybatis执行语句的名称,与Mapper接口一一对应,此属性为必须属性,且在命名空间(mapper标签的namespace)中唯一。
useGeneratedKeys 该属性是获取数据库内部生产的主键,默认为false。
keyProperty 赋值主键的属性名,即把数据库内部生产的主键赋值给该属性。
keyColumn 赋值主键的字段名,即把数据库内部生产的主键赋值给该字段。
parameterType 该属性的含义就是其字面意思,即传入语句的参数类型,是类的全限定类名,非必须。
flushCache 表示执行该语句将清空一级、二级缓存,默认为true。
timeout 超时时间,即程序提交sql语句到数据库等待的时间,超过此设置时间将抛出超时异常,默认设置是不超时,也就是说程序会一直等待直到有结果返回,单位为妙。
前四个标签是非常核心的标签。

简单示例

<insert id="insertAgent">
    INSERT  INTO t_node_agent (host_name, os_type, created_date)
    VALUES (#{hostName}, #{osType}, #{createdDate})
</insert>

返回主键–自增(mysql)

<insert id="insertAgent" parameterType="com.wht.demo.dao.vo.AgentVo" 
		useGeneratedKeys="true" keyProperty="nodeId" keyColumn="node_id">
    INSERT  INTO t_node_agent (host_name, os_type, created_date)
    VALUES (#{hostName}, #{osType}, #{createdDate})
</insert>

Java可在入参的vo中,get到对应的属性

返回主键–非自增
有些时候可能不用自增主键,例如oracle的序列,还有些是业务生成的规则生成主键等。
order mysql使用AFTER,oracle使用BEFORE

<insert id="insertAgent" parameterType="com.wht.demo.dao.vo.AgentVo" 
		useGeneratedKeys="true" keyProperty="nodeId" keyColumn="node_id">
	
	<selectKey keyColumn="node_id" resultType="long" keyProperty="nodeId" order="AFTER">
        SELECT LAST_INSERT_ID()
    </selectKey>
    INSERT  INTO t_node_agent (node_id,host_name, os_type, created_date)
    VALUES (#{nodeId},#{hostName}, #{osType}, #{createdDate})
</insert>

Java可在入参的vo中,get到对应的属性

posted @ 2023-04-27 21:48  红尘过客2022  阅读(67)  评论(0编辑  收藏  举报