Mybatis學(xué)習(xí)的一些細(xì)節(jié)

一.mybatis 基本配置

最近幾天一直在學(xué)習(xí)mybatis,看了一些源碼,本文講述mybatis的一些基本配置和基本的用法和注意到一些細(xì)節(jié)。個人時間和精力有限,本文屬于流水賬類型,不成體系,算是自己的個人筆記吧。

1.本案例所使用的數(shù)據(jù)庫為mysql,數(shù)據(jù)庫的腳本代碼如下:

CREATE TABLE `message` (
  `ID` int(11) NOT NULL AUTO_INCREMENT COMMENT '主鍵',
  `COMMAND` varchar(16) DEFAULT NULL COMMENT '指令名稱',
  `DESCRIPTION` varchar(32) DEFAULT NULL COMMENT '描述',
  `CONTENT` varchar(2048) DEFAULT NULL COMMENT '內(nèi)容',
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;


INSERT INTO `message` VALUES (1, '查看', '精彩內(nèi)容', '精彩內(nèi)容');
INSERT INTO `message` VALUES (2, '段子', '精彩段子', '如果你的月薪是3000塊錢,請記得分成五份,一份用來買書,一份給家人,一份給女朋友買化妝品和衣服,一份請朋友們吃飯,一份作為同事的各種婚喪嫁娶的份子錢。剩下的2999塊錢藏起來,不要告訴任何人');
INSERT INTO `message` VALUES (3, '新聞', '今日頭條', '7月17日,馬來西亞一架載有298人的777客機(jī)在烏克蘭靠近俄羅斯邊界墜毀。另據(jù)國際文傳電訊社消息,墜毀機(jī)型為一架波音777客機(jī),機(jī)載約280名乘客和15個機(jī)組人員。\r\n烏克蘭空管部門隨后證實(shí)馬航MH17航班墜毀。烏克蘭內(nèi)政部幕僚表示,這一航班在頓涅茨克地區(qū)上空被擊落。馬來西亞航空公司確認(rèn),該公司從阿姆斯特丹飛往吉隆坡的MH17航班失聯(lián),并稱最后與該客機(jī)取得聯(lián)系的地點(diǎn)在烏克蘭上空。圖為馬航客機(jī)墜毀現(xiàn)場。');
INSERT INTO `message` VALUES (4, '娛樂', '娛樂新聞', '昨日,鄧超在微博分享了自己和孫儷的書法。夫妻同樣寫幸福,但差距很大。鄧超自己都忍不住感慨字丑:左邊媳婦寫的。右邊是我寫的??赐晡以僖膊恍腋A恕?);
INSERT INTO `message` VALUES (5, '電影', '近日上映大片', '《忍者神龜》[2]真人電影由美國派拉蒙影業(yè)發(fā)行,《洛杉磯之戰(zhàn)》導(dǎo)演喬納森·里貝斯曼執(zhí)導(dǎo)。 \r\n片中四只神龜和老鼠老師都基于漫畫和卡通重新繪制,由動作捕捉技術(shù)實(shí)現(xiàn)。\r\n其中皮特·普勞澤克飾演達(dá)芬奇(武器:武士刀),諾爾·費(fèi)舍飾演米開朗基羅(武器:雙節(jié)棍),阿倫·瑞奇森飾演拉斐爾(武器:鐵叉),杰瑞米·霍華德飾演多拉泰羅(武器:武士棍)。\r\n該片計(jì)劃于2014年8月8日在北美上映。');
INSERT INTO `message` VALUES (6, '彩票', '中獎號碼', '查啥呀查,你不會中獎的!');

2.創(chuàng)建實(shí)體類

public class Message {
    /**
     * 主鍵
     */
    private String id;
    /**
     * 指令名稱
     */
    private String command;
    /**
     * 描述
     */
    private String description;
    /**
     * 內(nèi)容
     */
    private String content;
    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 getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
}


3.去官網(wǎng)下載mybatis ,導(dǎo)入相應(yīng)的jar包。

創(chuàng)建配置文件configuration.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>
<!-- 
 <settings>
   <setting name="useGeneratedKeys" value="false"/>
   <setting name="useColumnLabel" value="true"/>
 </settings>

 <typeAliases>
   <typeAlias alias="UserAlias" type="org.apache.ibatis.submitted.complex_property.User"/>
 </typeAliases> -->
 
 <environments default="development">
   <environment id="development">
     <transactionManager type="JDBC">
       <property name="" value=""/>
     </transactionManager>
     <dataSource type="UNPOOLED">
       <property name="driver" value="com.mysql.jdbc.Driver"/>
       <property name="url" value="jdbc:mysql://127.0.0.1:3306/micro_message"/>
       <property name="username" value="root"/>
       <property name="password" value="123"/>
     </dataSource>
   </environment>
 </environments>
 
 <mappers>
   <mapper resource="com/imooc/config/sqlxml/Message.xml"/>
   <mapper resource="com/imooc/config/sqlxml/Command.xml"/>
   <mapper resource="com/imooc/config/sqlxml/CommandContent.xml"/>
 </mappers>

</configuration>

這個配置文件,需要一個對象跟數(shù)據(jù)庫交互,這個對象是sqlsession,下面講述sqlsession.

二.Sqlsession對象

Sqlsession的作用:

    1. 向sql 語句傳入?yún)?shù)
    1. 執(zhí)行 sql語句
    1. 獲取執(zhí)行sql語句的結(jié)果
    1. 事物的控制

如何獲取Sqlsession:

    1. 通過獲取配置文件獲取數(shù)據(jù)庫連接相關(guān)信息
    1. 通過配置信息構(gòu)建 sqlSessionFactory 的對象
    1. 通過sqlsessionFactory大家數(shù)據(jù)庫會話。
public SqlSession getSqlSession() throws IOException {
        // 通過配置文件獲取數(shù)據(jù)庫連接信息
        Reader reader = Resources.getResourceAsReader("com/forzp/config/Configuration.xml");
        // 通過配置信息構(gòu)建一個SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        // 通過sqlSessionFactory打開一個數(shù)據(jù)庫會話
        SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession;
    }

3.SQL基本配置、執(zhí)行

Message.xml文件配置:

<mapper namespace="Message">

  <resultMap type="com.imooc.bean.Message" id="MessageResult">
    <id column="ID" jdbcType="INTEGER" property="id"/>
    <result column="COMMAND" jdbcType="VARCHAR" property="command"/>
    <result column="DESCRIPTION" jdbcType="VARCHAR" property="description"/>
    <result column="CONTENT" jdbcType="VARCHAR" property="content"/>
  </resultMap>

</mapper>

<select id="queryMessageList" parameterType="com.imooc.bean.Message" resultMap="MessageResult">
    select <include refid="columns"/> from MESSAGE
    <where>
        <if test="command != null and !&quot;&quot;.equals(command.trim())">
            and COMMAND=#{command}
        </if>
        <if test="description != null and !&quot;&quot;.equals(description.trim())">
            and DESCRIPTION like '%' #{description} '%'
        </if>
    </where>
  </select>

其中使用到了ONGL表達(dá)式:

WX20161225-220301@2x.png
WX20161225-220208@2x.png

在configuration.xml中配置

 <mappers>
    <mapper resource="com/imooc/config/sqlxml/Message.xml"/>
  
  </mappers>


執(zhí)行:

/**
     * 根據(jù)查詢條件查詢消息列表
     */
    public List<Message> queryMessageList(String command,String description) {
        DBAccess dbAccess = new DBAccess();
        List<Message> messageList = new ArrayList<Message>();
        SqlSession sqlSession = null;
        try {
            sqlSession = dbAccess.getSqlSession();
            Message message = new Message();
            message.setCommand(command);
            message.setDescription(description);
            // 通過sqlSession執(zhí)行SQL語句
            messageList = sqlSession.selectList("Message.queryMessageList",message);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if(sqlSession != null) {
                sqlSession.close();
            }
        }
        return messageList;
    }

三、log4j動態(tài)調(diào)試SQL

由于mybatis的sql語句寫在了xml中,導(dǎo)致調(diào)試比較困難,不能打斷點(diǎn)。這時需要日志去調(diào)。

下載log4j jar包,并配置log4j.propertites

log4j.rootLogger=DEBUG,Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.org.apache=INFO

log的級別:

log.debug

log.info

log.warm

log.error

級別從小到大,也就是og4j.rootLogger=DEBUG;可以輸出所有的日志類型;og4j.rootLogger=info ,只能夠輸出 info,warm ,error

要想mybtis 顯示日志,必須log4j.rootLogger=DEBUG;
項(xiàng)目中配置了log4j,mybatis 會自動應(yīng)用log4j

四、一些其他的知識點(diǎn)

mybatis sql配置文件常用的標(biāo)簽如下:

WX20161226-213750@2x.png

mapper文件下的標(biāo)簽含義:

nameSpace 標(biāo)簽區(qū)分可以用來區(qū)分sql文件

parameterType 將會傳入這條語句的參數(shù)類的完全限定名或別名。這個屬性是可選的,因?yàn)?MyBatis 可以通過 TypeHandler 推斷出具體傳入語句的參數(shù),默認(rèn)值為 unset。

resultMap 外部 resultMap 的命名引用。結(jié)果集的映射是 MyBatis 最強(qiáng)大的特性,對其有一個很好的理解的話,許多復(fù)雜映射的情形都能迎刃而解。使用 resultMap 或 resultType,但不能同時使用。

五、一對多sql xml的配置

java實(shí)體內(nèi)Command包含了一個List<CommandContent> contentList集合。


public class Command {
    /**
     * 主鍵
     */
    private String id;
    /**
     * 指令名稱
     */
    private String name;
    /**
     * 描述
     */
    private String description;
    /**
     * 一條指令對應(yīng)的自動回復(fù)內(nèi)容列表
     */
    private List<CommandContent> contentList;
    
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public List<CommandContent> getContentList() {
        return contentList;
    }
    public void setContentList(List<CommandContent> contentList) {
        this.contentList = contentList;
    }
}

在mapper中配置:

<mapper namespace="Command">
  <resultMap type="com.imooc.bean.Command" id="Command">
    <id column="C_ID" jdbcType="INTEGER" property="id"/>
    <result column="NAME" jdbcType="VARCHAR" property="name"/>
    <result column="DESCRIPTION" jdbcType="VARCHAR" property="description"/>
    <collection property="contentList"  resultMap="CommandContent.Content"/>
  </resultMap>
  
  <select id="queryCommandList" parameterType="com.imooc.bean.Command" resultMap="Command">
    select a.ID C_ID,a.NAME,a.DESCRIPTION,b.ID,b.CONTENT,b.COMMAND_ID
    from COMMAND a left join COMMAND_CONTENT b
    on a.ID=b.COMMAND_ID
    <where>
        <if test="name != null and !&quot;&quot;.equals(name.trim())">
            and a.NAME=#{name}
        </if>
        <if test="description != null and !&quot;&quot;.equals(description.trim())">
            and a.DESCRIPTION like '%' #{description} '%'
        </if>
    </where>
  </select>
  
</mapper>

CommandContent.xml配置

<mapper namespace="CommandContent">
  <resultMap type="com.imooc.bean.CommandContent" id="Content">
    <id column="ID" jdbcType="INTEGER" property="id"/>
    <result column="CONTENT" jdbcType="VARCHAR" property="content"/>
    <result column="COMMAND_ID" jdbcType="VARCHAR" property="commandId"/>
  </resultMap>
</mapper>

經(jīng)過這樣的配置,在DAO層執(zhí)行,就可以取出command中的屬性。

六.取自增長 key

<insert id="insert" parameterType="com.imooc.bean.Command" useGeneratedKeys="true" keyProperty="id">
  insert into Command (name,description) values(#{name},#{description});
 </insert>

七、一點(diǎn)細(xì)節(jié)

#{} 和${}區(qū)別:
#{}相當(dāng)于preparedStatment;
${}相當(dāng)于statment,它主要用于排序oderby 

另外:

敲黑板劃重點(diǎn),mybatis的所有知識都可以在官網(wǎng)上都有,建議看十遍,……_,地址:http://www.mybatis.org/mybatis-3/zh/configuration.html

關(guān)注我:

image
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容