MyBatis InsertAndget
2020-07-22 本文已影响0人
Doooook
Role.java
@Data
public class Role {
private Integer id;
private String roleName;
private String note;
private Byte status;
private Date created;
private Date modified;
}
RoleMapper.java
public interface RoleMapper {
int insertAndGetOne(Role role);
int insertAndGetTwo(Role role);
int insertAndGetThree(Role role);
}
RoleMapper.xml
<!-- 插入后获取主键 -->
<insert id="insertAndGetOne" parameterType="com.pengjs.kkb.mybatis.model.Role" useGeneratedKeys="true" keyProperty="id">
insert into role (role_name, note)
values (#{roleName,jdbcType=VARCHAR}, #{note,jdbcType=VARCHAR})
</insert>
<insert id="insertAndGetTwo" parameterType="com.pengjs.kkb.mybatis.model.Role">
<selectKey keyProperty="id" resultType="java.lang.Integer" order="AFTER">
SELECT LAST_INSERT_ID()
</selectKey>
insert into role (role_name, note)
values (#{roleName,jdbcType=VARCHAR}, #{note,jdbcType=VARCHAR})
</insert>
<!--
在实际工作中没有我们想象的那么简单,需要根据一些特殊的关系设置ID的值,假设我们取消表role的ID的自增规则,我们的要求是:
如果表role中没有记录,则我们需要设置ID=1,否则我们就取最大的ID加2,来设置新的主键,对于一些特殊要求,MyBatis也提供了
对应的方法。
-->
<insert id="insertAndGetThree" parameterType="com.pengjs.kkb.mybatis.model.Role">
<selectKey keyProperty="id" resultType="java.lang.Integer" order="BEFORE">
select if(max(id) is null, 1, max(id) + 2) as newId from role
</selectKey>
insert into role (id, role_name, note)
values (#{id,jdbcType=INTEGER}, #{roleName,jdbcType=VARCHAR}, #{note,jdbcType=VARCHAR})
</insert>
测试
@Test
public void testInsertAndGet() {
Role role = new Role();
role.setRoleName("admin");
role.setNote("管理员");
int insertAndGetOne = roleMapper.insertAndGetOne(role);
System.out.println(role);
role.setRoleName("common");
role.setNote("普通员工");
int insertAndGetTwo = roleMapper.insertAndGetTwo(role);
System.out.println(role);
role.setRoleName("common1");
role.setNote("普通员工1");
int insertAndGetThree = roleMapper.insertAndGetThree(role);
System.out.println(role);
}