溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

使用Java怎么實現(xiàn)MyBatis接口編程

發(fā)布時間:2021-04-13 15:47:36 來源:億速云 閱讀:182 作者:Leah 欄目:編程語言

使用Java怎么實現(xiàn)MyBatis接口編程?相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。

要求:

1.配置文件的namespace名稱空間指定為接口的全類名

2.配置文件中的id唯一標識與接口中的方法對應(返回值類型對應,方法名對應,參數(shù)個數(shù)和類型對應)

接口代碼:

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}:從傳遞過來的參數(shù)中取出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 {
   //獲取接口的實現(xiàn)類對象
   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代表與數(shù)據(jù)庫的一次會話,用完要關閉

3. SqlSession和Connection都是非線程安全的,所以每次都要獲取新的對象,而不能寫成成員變量

4.mapper接口沒有實現(xiàn)類,但是MyBatis生成代理對象

看完上述內(nèi)容,你們掌握使用Java怎么實現(xiàn)MyBatis接口編程的方法了嗎?如果還想學到更多技能或想了解更多相關內(nèi)容,歡迎關注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI