1.看一下我们接口
package cn.bdqn.mybatis.dao; import org.apache.ibatis.annotations.Select; import cn.bdqn.mybatis.been.Emp; /** * 这个接口不用写实现类,是用来给empMapper.xml进行动态绑定的 * @author Administrator * */ public interface EmpMapper { public Emp getEmpById(Integer id); public void addEmp(Emp emp); /** * MyBatis允许增删改直接定义一下类型返回值 * int long boolean 以及相应的包装类, * 在接口中定义方法的时候,直接定义相应的返回值即可,无其他操作 * @param emp * @return */ public boolean updateEmp(Emp emp); public void deleteEmpById(Integer id); }
2.编写mapper
<?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="cn.bdqn.mybatis.dao.EmpMapper"> <!-- id,唯一标识 resultType:返回值类型,bean的全限定名称 #{id},从传递过来的参数中取出id值,相当于换位符 public Emp getEmpById(Integer id); --> <select id="getEmpById" resultType="cn.bdqn.mybatis.been.Emp" databaseId="mysql"> select * from emp where id = #{id} </select> <select id="getEmpById" resultType="cn.bdqn.mybatis.been.Emp" databaseId="oracle"> select * from emp where id = #{id} </select> <!-- public void addEmp(Emp emp); insert标签: id:对应我们javaBean的方法名 parameterType 可以省略,如果要写就是javaBean的全限定名称 insert into emp(last_name,gender,email) values(#{last_name},#{gender},#{email}) 结尾不需要分号,values值的#{对应的javaBean的属性名} --> <insert id="addEmp" parameterType="cn.bdqn.mybatis.been.Emp"> insert into emp(last_name,email,gender) values(#{last_name},#{email},#{gender}) </insert> <!-- update标签: public void updateEmp(Emp emp); id:对应我们javaBean的方法名 parameterType 可以省略,如果要写就是javaBean的全限定名称 update emp set last_name=#{last_name},email=#{email},gender=#{gender} while id=#{id} 结尾不需要分号,#{}相当于占位符,等于我们传过来的值 --> <update id="updateEmp"> update emp set last_name=#{last_name},email=#{email},gender=#{gender} where id=#{id} </update> <!-- delet标签: public void deleteEmpById(Integer id); --> <delete id="deleteEmpById"> delete from emp where id=#{id} </delete> </mapper>
3.编写测试类
package cn.bdqn.mybatis.test; import java.io.IOException; import java.io.InputStream; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import cn.bdqn.mybatis.been.Emp; import cn.bdqn.mybatis.dao.EmpMapper; public class MyBatisTest_02 { public static void main(String[] args) throws IOException { //获取SqlSessionFactory实例 String resource="mybatis-config.xml"; InputStream is = Resources.getResourceAsStream(resource); SqlSessionFactory build = new SqlSessionFactoryBuilder().build(is); //获取到的sqlsession不会自动提交 SqlSession openSession = build.openSession(); try{ //测试添加 EmpMapper mapper = openSession.getMapper(EmpMapper.class); /* Emp emp = new Emp(null,"liyuanfeng","liyuanfeng@qq.com","1"); mapper.addEmp(emp);*/ //测试修改 Emp emp = new Emp(1,"liyuanfeng","liyuanfeng@qq.com","1"); mapper.updateEmp(emp); //进行手动提交 openSession.commit(); }finally{ openSession.close(); } } }