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","[email protected]","1");
mapper.addEmp(emp);*/
//測試修改
Emp emp = new Emp(1,"liyuanfeng","[email protected]","1");
mapper.updateEmp(emp);
//進行手動送出
openSession.commit();
}finally{
openSession.close();
}
}
}