1. 程式人生 > 其它 >Mybatis框架入門

Mybatis框架入門

首先,先說一下寫這個入門程式的需求與開發步驟:

  1. 需求:使用Mybatis從資料庫中查詢出資料。   
  2. 開發步驟:   
    1. 準備MySQL資料庫,建立表結構新增一些資料
    2. 建立Java工程,匯入開發用的jar包
    3. 編寫實體類,和表結構對應,用來進行資料的封裝
    4. 編寫對映配置檔案(其中包括資料庫連線資訊),載入對映配置檔案
    5. 編寫入門的程式碼

那前三步就不說了有一些基礎就可以辦到

在寫配置檔案的時候,主要編寫兩種配置檔案,第一種為主配置檔案,管理其他和介面對應的配置檔案。

在編寫主配置檔案時,主要有兩點:

  1. 配置環境們(需要設定預設環境)
    <environments default="mysql">
  2. 配置具體環境
    <environment id="mysql">
    1. 配置事務型別
      <!--配置事務的型別,使用本地事務的策略-->
      <transactionManager type="JDBC"></transactionManager>
    2. 配置是否使用資料庫連線池
      <!--是否要使用連線池,內建的連線池-->
      <dataSource type="POOLED">
          <property name="driver" value="com.mysql.jdbc.Driver" />
          <property name="url" value="jdbc:mysql:///mybatis_01" />
          <property name="username" value="root" />
          <property name="password" value="root" />
      </dataSource>
    3. 引入對映配置檔案
      <mappers>
          <mapper resource="mappers/UserMapper.xml" />
          <mapper resource="mappers/AccountMapper.xml"/>
      </mappers>

在編寫對映配置檔案的時候,檔名與Mapper介面(也可以說是Dao介面為持久層介面)名要一致(算是一種規範).通過名稱空間來找到對應Mapper。

其對應id為其對應的方法,resultType為返回值型別。

mapper.xml的規範
<?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標籤中新增名稱空間
<mapper namespace="cn.mapper.UserMappper"></mapper>
在select標籤內寫對應的select語句

<select id="findAll" resultType="cn.tx.domain.User" >
    select * from account
</select>

最後進行測試:

  1. 載入主配置檔案(resources)
    InputStream inputStream= null;
    SqlSession session = null;
    AccountMapper accountMapper = null;
    UserMappper userMappper =null;
    //@Before註釋是將被註釋的程式碼放在最前面執行
    @Before
    public void init() throws IOException {
        inputStream= Resources.getResourceAsStream("SqlMapConfig.xml");
        //建立新的會話工廠
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
        //獲取會話
        session = factory.openSession();
        //獲取相應的代理物件
       // accountMapper = session.getMapper(AccountMapper.class);
        userMappper = session.getMapper(UserMappper.class);
    }
    //@After註釋是將被註釋的程式碼放在最後執行進行收尾工作
    @After
    public void destory() throws IOException {
        session.close();
        inputStream.close();
    }
  2. 建立會話工廠(sqlsessionFactory)
  3. 通過工廠獲取(sqlsession)
  4. 獲取代理物件進行操作
    @Test
    public void test(){
        //具體執行的操作
        List<Account> accounts = accountMapper.findAll();
        for (Account account : accounts) {
            System.out.println(account);
        }
    }