定义接口类:
package com.atChina.dao;
import com.atChina.bean.Employee;
public interface EmployeeMapper {
public Employee getEmployeeById(Integer depno);
public void addEmploy(Employee employee);
public Integer updateEmp(Employee employee);
public Integer deleteEmpById(Integer id);
}
sql映射文件,增删改查的实现
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace不能随便自定义了,应该是接口类的全限定名 -->
<mapper namespace="com.atChina.dao.EmployeeMapper">
<!-- id:唯一标识 ,应该是接口类中的抽象方法名
resultType: 返回值类型
#{deptno}:参数 {}中的deptno是占位符,起任何名字都行 -->
<select
id="getEmployeeById"
resultType="emp" >
select * from DEPTTEST where deptno = #{deptno}
</select>
<!-- parameterType可以省略不写 -->
<insert id="addEmploy" parameterType="com.atChina.bean.Employee">
insert into DEPTTEST(deptno, dname, loc) values(#{deptno}, #{dname}, #{loc})
</insert>
<update id="updateEmp">
update DEPTTEST a set dname=#{dname}, loc=#{loc}
where deptno = #{deptno}
</update>
<delete id="deleteEmpById">
delete from DEPTTEST a where deptno = #{deptno}
</delete>
</mapper>
测试:
/*
* 测试增删改
* 1. mybatis允许增删改直接定义以下数据类型返回值
* Integer, Long, Boolean,或者对一个的基本类型
*/
@Test
public void test03() throws IOException{
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
// 不会自动提交
SqlSession openSession = sqlSessionFactory.openSession();
try{
Employee e = new Employee();
e.setDeptno(50);
e.setDname("hehe");
e.setLoc("earth");
EmployeeMapper em = openSession.getMapper(EmployeeMapper.class);
//em.addEmploy(e); 增加一条数据
//em.updateEmp(e); 更新数据
Integer delete = em.deleteEmpById(50); // 删除数据
System.out.println(delete);
// 提交数据
openSession.commit();
}finally{
openSession.close();
}
}