使用MyBatis的注意事項有哪些

农民小工程师發表於2024-06-13

這篇文章給大家分享的是有關使用MyBatis的注意事項有哪些的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

一、MyBatis的HelloWord

1.根據xml配置檔案(全域性配置檔案mybatis-config.xml)建立一個SqlSessionFactory物件 有資料來源一些執行環境資訊

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
 PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
   <environments default="development">
      <environment id="development">
         <transactionManager type="JDBC" />
         <dataSource type="POOLED">
            <property name="driver" value="com.mysql.jdbc.Driver" />
            <property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
            <property name="username" value="root" />
            <property name="password" value="123456" />
         </dataSource>
      </environment>
   </environments>
   <!-- 將我們寫好的sql對映檔案(EmployeeMapper.xml)一定要註冊到全域性配置檔案(mybatis-config.xml)中 -->
   <mappers>
      <mapper resource="EmployeeMapper.xml" />
   </mappers>
</configuration>

2.sql對映檔案EmployeeMapper.xml;配置了每一個sql,以及sql的封裝規則等。

<?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">
<mapper namespace="com.atguigu.mybatis.dao.EmployeeMapper">
<!-- 
namespace:名稱空間;指定為介面的全類名
id:唯一標識
resultType:返回值型別
#{id}:從傳遞過來的引數中取出id值

public Employee getEmpById(Integer id);
分離實現與介面
 -->
   <select id="getEmpById" resultType="com.atguigu.mybatis.bean.Employee">
      select id,last_name lastName,email,gender from tbl_employee where id = #{id}
   </select>
</mapper>

3.將sql對映律飛俠檔案註冊在全域性配置檔案mybatis-config.xml中

<mappers>
   <mapper resource="EmployeeMapper.xml" />
</mappers>

4.寫程式碼:

1).根據全域性配置檔案得到SqlSessionFactory;

String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

2).使用sqlSession工廠,獲取到sqlSession物件使用他來執行增刪改查,一個sqlSession就是代表和資料庫的一次會話,用完關閉

SqlSession openSession = sqlSessionFactory.openSession();

3).使用sql的唯一標誌來告訴MyBatis執行哪個sql。sql都是儲存在sql對映檔案中的

try {
   Employee employee = openSession.selectOne(
         "com.atguigu.mybatis.dao.EmployeeMapper.getEmpById", 1); // spacename + sqlId
   System.out.println(employee);
} finally {
   openSession.close();
}

二、MyBatis介面式程式設計

mybatis:    Mapper.java(介面) ====>  xxMapper.xml(實現)

介面式程式設計的好處在於,能夠將功能與實現相分離

1、SqlSession代表和資料庫的一次會話;用完必須關閉;
2、SqlSession和connection一樣它都是非執行緒安全。每次使用都應該去獲取新的物件。
3、mapper.java介面沒有實現類,但是mybatis會為這個介面生成一個代理物件。(將介面和xml進行繫結)
EmployeeMapper empMapper = sqlSession.getMapper(EmployeeMapper.class);
4、兩個重要的配置檔案:

  • mybatis的全域性配置檔案:包含資料庫連線池資訊,事務管理器資訊等…系統執行環境資訊

  • sql對映檔案:儲存了每一個sql語句的對映資訊:將sql抽取出來。

感謝各位的閱讀!關於“使用MyBatis的注意事項有哪些”這篇文章就分享到這裡了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

相關文章