MyBatis-插入时获取自增主键以及非自增主键

  • 1.Dao接口
package com.edu.dao;
import com.edu.bean.Employee;
public interface EmployeeDao {
	public Employee getEmpById(Integer id);
	public int updateEmployee(Employee employee);
	public boolean deleteEmployee(Integer id);
	public int insertEmployee(Employee employee);
	public int insertEmployeeAutoFillId(Employee employee);
}

  • 2.Dao配置


  
  
  
  
  	
  	
  		update t_employees
  			set empName=#{empName},gender=#{gender},email=#{email} 
  			where id=#{id}
  	
  	
  		delete from t_employees where id=#{id}
  	
  
  	
  	
  	 
  		insert into t_employees(empName,gender,email) values(#{empName},#{gender},#{email})
  	
  	
  	
  		
	  	
  			select max(id)+1 from t_employees
	  	
  		insert into t_employees(id,empName,gender,email) values(#{id},#{empName},#{gender},#{email})
  	
  
  • 3.测试
public class MyBatisCRUDTest {
	
	SqlSessionFactory factory;
	
	@Before
	public void initSqlSessionFactory() {
		String resource = "mybatis-config.xml";
		InputStream  is = null;
		try {
			is=Resources.getResourceAsStream(resource);
			factory = new SqlSessionFactoryBuilder().build(is);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

@Test
	public void testInsertAutoIncreatment() {
		SqlSession sqlSession = factory.openSession();
		try {
			EmployeeDao employeeDao = sqlSession.getMapper(EmployeeDao.class);
			Employee employee = new Employee(null, "Tommy", "[email protected]", 1, "tommyAccount");
			employeeDao.insertEmployee(employee);
			System.out.println(" id=== " + employee.getId());
			sqlSession.commit();
		}catch (Exception e) {
		}finally {
			sqlSession.close();
		}
	}
	@Test
	public void testInsertNoAutoIncreatment() {
		SqlSession sqlSession = factory.openSession();
		try {
			EmployeeDao employeeDao = sqlSession.getMapper(EmployeeDao.class);
			Employee employee = new Employee(null, "Tommy", "[email protected]", 1, "tommyAccount");
			employeeDao.insertEmployeeAutoFillId(employee);
			System.out.println(" id=== " + employee.getId());
			sqlSession.commit();
		}catch (Exception e) {
		}finally {
			sqlSession.close();
		}
	}
}

你可能感兴趣的:(MyBatis)