1. 程式人生 > 程式設計 >Java框架MyBatis介面程式設計過程解析

Java框架MyBatis介面程式設計過程解析

要求:

1.配置檔案的namespace名稱空間指定為介面的全類名

2.配置檔案中的id唯一標識與介面中的方法對應(返回值型別對應,方法名對應,引數個數和型別對應)

介面程式碼:

package com.bird.mybatis.dao;
import com.bird.mybatis.bean.Employee;
public interface EmployeeMapper {
 public Employee getEmpById(Integer id); 
}

對應配置檔案程式碼:

<?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:名稱空間(若使用介面式程式設計,與EmployeeMapper介面全類名一致)
 id:唯一標識(與介面中的方法名對應)
 resultType:返回值型別(與對應方法的返回值對應)
 #{id}:從傳遞過來的引數中取出id值
 -->
<mapper namespace="com.bird.mybatis.dao.EmployeeMapper">
 <select id="getEmpById" resultType="com.bird.mybatis.bean.Employee"> 
  select id,last_name lastName,gender,email from tbl_employee where id = #{id}
 </select>
</mapper>

測試程式碼:

/**
  * MyBatis介面程式設計
  * @throws IOException 
  */
 @Test
 void test2() throws IOException {
  //獲取sqlSessionFactory物件
  SqlSessionFactory ssf = getSqlSessionFactory();
  //獲取sqlSession物件
  SqlSession openSession = ssf.openSession();
  try {
   //獲取介面的實現類物件
   EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
   Employee empById = mapper.getEmpById(1);
   System.out.println(empById);
  }finally {
   openSession.close();
  }
 }
 
 /**
  * 獲取sqlSessionFactory物件
  * @throws IOException 
  */
 public static SqlSessionFactory getSqlSessionFactory() throws IOException {
  String resource = "mybatis-config.xml";
  InputStream is = Resources.getResourceAsStream(resource);
  return new SqlSessionFactoryBuilder().build(is);
 }

總結:

1.介面程式設計:

原生介面: Dao ===> DaoImpl

MyBatis: Dao ===> Mapper.xml

2. SqlSession代表與資料庫的一次會話,用完要關閉

3. SqlSession和Connection都是非執行緒安全的,所以每次都要獲取新的物件,而不能寫成成員變數

4.mapper介面沒有實現類,但是MyBatis生成代理物件

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。