UUID怎么在MyBatis中生成

今天就跟大家聊聊有关UUID怎么在MyBatis中生成,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

1.<selectKey>标签属性说明

  • keyProperty:设置需要自动生成键值的列

  • order:可选值BEFORE和AFTER,设置为BEFORE会先执行selectKey语句,设置keyProperty属性,再执行insert语句;设置为AFTER会先执行insert语句再执行selectKey语句

  • resultType:结果类型,MyBatis 通常可以自己检测到,但这并不影响给它一个确切的类型。MyBatis 允许使用任何基本的数据类型作为键值,也包括String 类型。

  • statementType:支持STATEMENT、PREPARED 和CALLABLE 语句类型,分别对应Statement, PreparedStatement 和CallableStatement

2.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>

3.注解方式

使用@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);

测试代码:

User user = new User();
user.setUser_age(22);
user.setUser_sex(1);
int count = userMapper.save(user); 
System.out.println("count:" + count);
System.out.println("id:" + user.getId());

看完上述内容,你们对UUID怎么在MyBatis中生成有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注行业资讯频道,感谢大家的支持。