一. 问题分析
有时候对数据库进行增删改,想要它返回一个影响条数,判断它能不能正常执行。
二. 知识储备
只需将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();
}
}