1 首先在Mapper.xml配置
<!-- parameterType:参数类型,可以省略,
获取自增主键的值:
mysql支持自增主键,自增主键值的获取,mybatis也是利用statement.getGenreatedKeys();
useGeneratedKeys="true";使用自增主键获取主键值策略
keyProperty;指定对应的主键属性,也就是mybatis获取到主键值以后,将这个值封装给javaBean的哪个属性
-->
<insert id="addEmp" parameterType="com.atguigu.mybatis.bean.Employee"
useGeneratedKeys="true" keyProperty="id" databaseId="mysql">
insert into tbl_employee(last_name,email,gender)
values(#{lastName},#{email},#{gender})
</insert>
<select id="getEmpById" resultType="com.atguigu.mybatis.bean.Employee"
databaseId="mysql">
select * from tbl_employee where id = #{id}
</select>
<update id="updateEmp">
update tbl_employee
set last_name=#{lastName},email=#{email},gender=#{gender}
where id=#{id}
</update>
<delete id="deleteEmpById">
delete from tbl_employee where id=#{id}
</delete>
2在映射java类中添加对应方法
public Employee getEmpById(Integer id);
public Long addEmp(Employee employee);
public boolean updateEmp(Employee employee);
public boolean deleteEmpById(Integer id);
3在junit测试方法执行
public SqlSessionFactory getSqlSessionFactory() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
return new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void test03() throws IOException{
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
//1、获取到的SqlSession不会自动提交数据
SqlSession openSession = sqlSessionFactory.openSession();
try{
EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
//测试添加
Employee employee = new Employee(null, "jerry4",null, "1");
Employee employee2 = new Employee(null, "jerry2",null, "1");
mapper.addEmp(employee2);
Long a=mapper.addEmp(employee);
System.out.println(employee.getId());
System.out.println(a);
// //测试修改
// Employee employee1 = new Employee(1, "Tom", "jerry@atguigu.com", "0");
// boolean updateEmp = mapper.updateEmp(employee1);
// System.out.println(updateEmp);
// //测试删除
// boolean updateEmp1= mapper.deleteEmpById(2);
// if(updateEmp1==true){
// System.out.println("删除成功");
// }
//2、手动提交数据
openSession.commit();
}finally{
openSession.close();
}
}