如何使用mybatis《一》,使用mybatis《一》

來源:互聯網
上載者:User

如何使用mybatis《一》,使用mybatis《一》

mybatis作為ORM輕量級架構一出現就吸引了無數人的眼球,比hibernate要簡單且入門較容易,下面開始我的第一個mybatis程式。

一、下載mybatis的包

我們知道任何一個架構都會有其包,我們從其官方網站下載其包,官網網址為:http://www.mybatis.org/mybatis-3/,我這裡使用的版本為3.3.0。下載完成之後解壓可看到如下的目錄結構:

 

mybatis-3.3.0.jar是其包,lib目錄下是其依賴包,我們把這些包放到我們的項目中。我這裡建立的是javaweb項目,方便以後做web測試,編寫的程式是普通的java程式。

二、配置環境

把mybatis的包放到項目的lib目錄下之後,接下來時配置mybatis的環境,我們知道mybatis做為ORM架構,屬於開發中的DAO層,是和資料庫打交道的,所以我們必須有資料,這裡以mysql資料為例,具體的建庫和建表這裡不闡述。

在src目錄下建立mybatis的設定檔,檔案名稱為:configuratin.xml,檔案內容如下:

<?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><!--別名-->         
<typeAliases> <typeAlias alias="Message" type="com.cn.imooc.entity.Message"/> </typeAliases> <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://127.0.0.1:3306/weixin?useUnicode=true&characterEncoding=UTF-8" /> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments><!--對應檔-->
<mappers> <mapper resource="com/cn/mappers/message.xml"/> </mappers> </configuration>

在mybatis設定檔中還有很多的配置項這裡僅僅使用了這幾個,

<typeAliases>  別名配置,即把實體類做個別名,目的在於在對應檔中使用實體類時不使用全限類名,而是使用別名,起到簡單的作用

<environments>  配置了一些環境 比如資料配置,這裡我們配置了資料來源

<mappers> 配置對應檔,這裡配置了com.cn.mappers包下的message.xml對應檔

下面對Message實體類進行說明,此實體類裡是一些屬性,如下,

package com.cn.imooc.entity;public class Message {    private String id;    private String command;    private String description;    private String comment;    public String getId() {        return id;    }    public void setId(String id) {        this.id = id;    }    public String getCommand() {        return command;    }    public void setCommand(String command) {        this.command = command;    }    public String getDescription() {        return description;    }    public void setDescription(String description) {        this.description = description;    }    public String getComment() {        return comment;    }    public void setComment(String comment) {        this.comment = comment;    }    @Override    public String toString() {        return "Message [id=" + id + ", command=" + command + ", description="                + description + ", comment=" + comment + "]";    }    }

提供了getXXX和setXXX方法,其中setXXX方法很關鍵,我這裡的屬性和資料庫的欄位名是一致,可以方便使用mybatis查詢出結果之後反射到實體類中,當然也可以和資料庫表欄位名不一致,後續會進行說明。

message.xml對應檔如下,

<mapper namespace="com.cn.inter.IMessageOperation">     <select id="selectUserByID" parameterType="int" resultType="com.cn.imooc.entity.Message">         select * from `message` where id = #{id}     </select>          <select id="selectMessages"  resultType="Message">         select id,                command,                description,                comment                from message;              </select></mapper>

這是我的mapper對應檔,裡邊有兩個方法,一個是:selectUserById 根據id查詢,另一個是selectMessages 查詢所有

好了,到此為止,我們的mybatis的環境搭建完成,下面可以進行測試了。

三、測試

下面是測試代碼,

package com.cn.test;import java.io.IOException;import java.io.Reader;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import com.cn.imooc.entity.Message;public class MyTest {    public static void main(String[] args) {        // TODO Auto-generated method stub         Reader reader;        SqlSession sqlSession=null;        try {            //1、獲得sqlSessionFactory            reader = Resources.getResourceAsReader("Configuration.xml");            SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);            //2、獲得sqlSession             sqlSession=sqlSessionFactory.openSession();            //3、查詢            Message message=sqlSession.selectOne("com.cn.inter.IMessageOperation.selectUserByID", 1);            System.out.println(message);        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        finally{            sqlSession.close();        }            }}

從上面可以看出,首先需要一個SqlSessionFactory,然後由sqlSessionFactory獲得sqlSession,由sqlSession執行查詢,使用了selectOne方法,第一個參數是對應檔中的nameSpace+“.”方法名,第二個參數是查詢參數。

至此,一個mybatis程式就寫完了,後續還會介紹別的版本。

有不當之處歡迎指正

謝謝

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.