Mybatis 学习笔记之 新增(二)

添加用户 自增主键返回


UserMapper.xml

  1. #{ } :指定 pojo 属性名,接收到 pojo 对象的属性值,mybatis 通过 OGNL 获取对象的属性值。
  2.  mysql 自增主键,执行 insert 提交之前自动生成一个自增主键。
  3. 通过 mysql 函数获取到刚插入记录的自增主键: LAST_INSERT_ID(),是 insert 之后调用此函数
<insert id="insertUser" parameterType="com.po.User">
<!-- 
将插入数据的主键返回,返回到对象中
select last_insert_id():得到刚 insert 记录的主键id,只适用在主键自增。
keyProperty:将查询到的主键值  设置到 parameterType 指定的对象哪个属性中。
order:select last_insert_id()的 执行顺序,相对于 insert 语句的  执行顺序。
resultType: 指定 select last_insert_id() 的结果类型
 -->
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
select last_insert_id()
</selectKey>
insert into user(name,sex,address) values(#{name},#{sex},#{address})
</insert>


Test类

@Test
	public void insertUserTest(){
		
		String resource = "sqlMapConfig.xml";
		InputStream inputStream;
		SqlSession sqlSession;
		try {
			inputStream = Resources.getResourceAsStream(resource);
			//创建会话工厂,传入 myBatis 配置信息
			SqlSessionFactory  sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
			
			sqlSession = sqlSessionFactory.openSession();
			
			//通过sqlSession 操作数据库
			
			User user = new User();
			user.setName("LawJack");
			user.setSex("male");
			user.setAddress("Town China");
			 sqlSession.insert("test.insertUser",user);
			
			 //提交事务
			 sqlSession.commit();
			 
			 //返回自增主键
			System.out.println(user.getId());
			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			sqlSession.close();
		}
		
		
	}

注意: 增、删、改 都需要,提交事务



非自增主键返回(uuid)

UserMapper.xml

使用 mysql 的 uuid() 函数生成主键,需要修改表中 id 字段类型为 string,长度设置成 35 位。


执行思路:
先通过 uuid() 查询到主键,将主键输入 到 sql 语句中。


执行 uuid() 语句顺序相对于 insert 语句之前执行。

<!-- 
执行过程:
首先 通过 MySQL 的 uuid() 获取主键,将主键设置到user对象的id 属性中;
在 insert 执行时,从 user对象中取出 id 属性值
 -->
<selectKey keyProperty = "id" order="BEFORE"  resultType="java.lang.String">
select uuid()
</selectKey>


猜你喜欢

转载自blog.csdn.net/qq_30715329/article/details/79893591
今日推荐