mybatis主键UUID的策略
<selectKey>标签属性
keyProperty:设置需要自动生成键值的列
order:可选值BEFORE和AFTER,设置为BEFORE会先执行selectKey语句,设置keyProperty属性,再执行insert语句;设置为AFTER会先执行insert语句再执行selectKey语句
resultType:结果类型,MyBatis 通常可以自己检测到,但这并不影响给它一个确切的类型。MyBatis 允许使用任何基本的数据类型作为键值,也包括String 类型
statementType:支持STATEMENT、PREPARED 和CALLABLE 语句类型,分别对应Statement, PreparedStatement 和CallableStatement
XML方式(mysql数据库为例)
使用<selectKey>标签,keyProperty设置生成的UUID所绑定的属性,如设置为id,即会将值绑定到参数对象User的id属性上;order属性设置为BEFORE,先执行selectKey语句
<insert id="save" parameterType="User"> <selectKey keyProperty="id" resultType="string" order="BEFORE"> select replace(uuid(), '-', '') as id from dual </selectKey> insert into t_user(id, user_sex) values( #{id}, #{user_sex} ) </insert>
注解方式
使用@SelectKey注解,属性和<selectKey>标签类似。before属性设置为true,类似于<selectKey>标签order属性设置为BEFORE
@Insert("insert into t_user(id, user_sex) values(#{id}, #{user_sex})")
@SelectKey(keyProperty = "id", resultType = String.class, before = true,
statement = "select replace(uuid(), '-', '') as id from dual")
public int save(User user);
参考:
https://blog.csdn.net/mytt_10566/article/details/78505719
立志如山 静心求实
浙公网安备 33010602011771号