Day11——增删改操作获取对数据库的影响条数

一. 问题分析

有时候对数据库进行增删改,想要它返回一个影响条数,判断它能不能正常执行。

二. 知识储备

只需将Mapper接口的返回值类型改为你想要获取的类型即可。比如Integer、Long、Boolean。

三. 例子

如下:
EmployeeMapper.java

package com.atguigu.mybatis.dao;

import com.atguigu.mybatis.beans.Employee;

public interface EmployeeMapper {

	public Employee selectEmployeeById(Integer id);
	
    public Integer insertEmployee(Employee employee);
    
    public Long updateEmployee(Employee employee);
    
    public Boolean deleteEmployeeById(Integer id);
	
}

TestMyBatis.java

@Test
	public void testReturnKeys() throws Exception{
		SqlSessionFactory ssf = getSqlSessionFactory();
		SqlSession session = ssf.openSession();
		//ssf.openSession(true);带自动提交功能
		try {
			EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
			Employee employee = new Employee(null, "优优", "yy@sina.com", "1");
			
			Integer result = mapper.insertEmployee(employee);
			System.out.println("对数据库的影响:" + result);
			
			Integer id = employee.getId();
			System.out.println("主键值:" + id);
			
			session.commit();
			
			
			/**
			 * 底层源码实现主键自增并且返回主键
			 */
//			
//			Connection conn = null;
//			PreparedStatement ps = 
//					conn.prepareStatement("sql语句", PreparedStatement.RETURN_GENERATED_KEYS);
//			ps.executeUpdate();
//			ps.getGeneratedKeys();
			
		} finally {
			// TODO: handle finally clause
			session.close();
		}
		
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值