1. 程式人生 > >MyBatis學習筆記(二)- 介面式程式設計

MyBatis學習筆記(二)- 介面式程式設計

MyBatis 的 HelloWorld 的進階

注意:本次操作是在上一個筆記的基礎之上

工程目錄如下:

1. 建立一個 EmployeeMapper 的介面

public interface EmployeeMapper {
	
	public Employee getEmpById(Integer id);

}

2. 修改 Mapper 檔案

<mapper namespace="www.xq.mybatis.dao.EmployeeMapper">
<!-- 
namespace:名稱空間;指定為介面的全類名
id:唯一標識
resultType:返回值型別
#{
id}:從傳遞過來的引數中取出id值 public Employee getEmpById(Integer id); --> <select id="getEmpById" resultType="www.xq.mybatis.bean.Employee"> select id,last_name lastName,email,gender from tbl_employee where id = #{id} </select> </mapper>

3. 測試

public SqlSessionFactory getSqlSessionFactory
() throws IOException { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); return new SqlSessionFactoryBuilder().build(inputStream); } @Test public void test01() throws IOException { // 1、獲取sqlSessionFactory物件 SqlSessionFactory sqlSessionFactory =
getSqlSessionFactory(); // 2、獲取sqlSession物件 SqlSession openSession = sqlSessionFactory.openSession(); try { // 3、獲取介面的實現類物件 //會為介面自動的建立一個代理物件,代理物件去執行增刪改查方法 EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class); Employee employee = mapper.getEmpById(1); System.out.println(mapper.getClass()); System.out.println(employee); } finally { openSession.close(); } }

mybatis HelloWorld 小結

  1. 介面式程式設計
    原生: Dao ====> DaoImpl
    mybatis: Mapper ====> xxMapper.xml

  2. SqlSession代表和資料庫的一次會話;用完必須關閉;

  3. SqlSession和connection一樣她都是非執行緒安全。每次使用都應該去獲取新的物件。

  4. mapper介面沒有實現類,但是mybatis會為這個介面生成一個代理物件。
    (將介面和xml進行繫結)
    EmployeeMapper empMapper = sqlSession.getMapper(EmployeeMapper.class);

  5. 兩個重要的配置檔案:
    mybatis的全域性配置檔案:包含資料庫連線池資訊,事務管理器資訊等…系統執行環境資訊
    sql對映檔案:儲存了每一個sql語句的對映資訊:
    將sql抽取出來。