映射文件-insert、update、delete

1.insert:在标签内写inser的sql语句

配置文件: 

 <insert id="addEmp" parameterType="cn.it.mybatis.bean.Employee">
  	INSERT INTO tbl_employee(last_name,gender,email) VALUE(#{lastName},#{gender},#{email})
  </insert>

测试代码:

        @Test
	void test02() throws IOException {
		SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();

		// 不自动提交数据
		// sqlSessionFactory.openSession(true)自动提交数据
		SqlSession openSession = sqlSessionFactory.openSession();


		try {
			EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);

			// 添加一个新员工
			mapper.addEmp(new Employee(null, "张三", "123@qq.com", "1"));

			// 手动提交数据
			openSession.commit();
		} finally {
			openSession.close();
		}
	}

执行结果:

 2.update:标签内写update的sql语句

配置文件:

<update id="updateEmp">
  	UPDATE tbl_employee 
  	SET last_name=#{lastName},gender=#{gender},email=#{email}
  	WHERE id=#{id}
  </update>

测试代码:

	@Test
	void test03() throws IOException {
		SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();

		SqlSession openSession = sqlSessionFactory.openSession();

		try {
			EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);

			// 修改1号员工信息
			mapper.updateEmp(new Employee(1, "李四", "789@qq.com", "1"));

			openSession.commit();

		} finally {
			openSession.close();
		}
	}

执行结果:

修改了id为1号的信息

 3.delete:在标签中写delete的sql语句

配置文件:

  <delete id="deleteEmp">
  	DELETE FROM tbl_employee WHERE id=#{id}
  </delete>

测试代码:

​
	@Test
	void test04() throws IOException {
		SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();

		SqlSession openSession = sqlSessionFactory.openSession();

		try {
			EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);

			// 删除1号员工信息
			mapper.deleteEmp(1);

			openSession.commit();

		} finally {
			openSession.close();
		}
	}

​

执行结果:

已经删除1号员工

 

MyBatis允许增删改直接定义以下类型的返回值,

Integer、Long、Boolean


 获取自增主键的值(仅对 insert 和 update 有用):

MySql支持自增主键,自增主键的值获取。而MyBatis也是使用statement.getGenreatedKeys(),来获取自增主键的值。

useGeneratedKeys="true":开启自增主键获取主键值的功能

keyProperty:指定对应的主键属性,也就是MyBatis获取到的主键值后,将这个值封装给javaBean的哪个属性。

如果是非自增的数据库:

可以使用selectKey使查询主键的sql提前运行,封装在javaBean的属性中,然后再在使用主键值

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值