一.mybatis 基本配置
最近幾天一直在學(xué)習(xí)mybatis坊罢,看了一些源碼民珍,本文講述mybatis的一些基本配置和基本的用法和注意到一些細(xì)節(jié)绍刮。個(gè)人時(shí)間和精力有限赦役,本文屬于流水賬類型,不成體系妇汗,算是自己的個(gè)人筆記吧帘不。
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塊錢杨箭,請(qǐng)記得分成五份寞焙,一份用來買書,一份給家人互婿,一份給女朋友買化妝品和衣服捣郊,一份請(qǐng)朋友們吃飯,一份作為同事的各種婚喪嫁娶的份子錢慈参。剩下的2999塊錢藏起來呛牲,不要告訴任何人');
INSERT INTO `message` VALUES (3, '新聞', '今日頭條', '7月17日,馬來西亞一架載有298人的777客機(jī)在烏克蘭靠近俄羅斯邊界墜毀驮配。另據(jù)國際文傳電訊社消息娘扩,墜毀機(jī)型為一架波音777客機(jī),機(jī)載約280名乘客和15個(gè)機(jī)組人員壮锻。\r\n烏克蘭空管部門隨后證實(shí)馬航MH17航班墜毀琐旁。烏克蘭內(nèi)政部幕僚表示,這一航班在頓涅茨克地區(qū)上空被擊落猜绣。馬來西亞航空公司確認(rèn)灰殴,該公司從阿姆斯特丹飛往吉隆坡的MH17航班失聯(lián),并稱最后與該客機(jī)取得聯(lián)系的地點(diǎn)在烏克蘭上空掰邢。圖為馬航客機(jī)墜毀現(xiàn)場(chǎng)牺陶。');
INSERT INTO `message` VALUES (4, '娛樂', '娛樂新聞', '昨日,鄧超在微博分享了自己和孫儷的書法尸变。夫妻同樣寫幸福义图,但差距很大。鄧超自己都忍不住感慨字丑:左邊媳婦寫的召烂。右邊是我寫的⊥蕹校看完我再也不幸福了奏夫。');
INSERT INTO `message` VALUES (5, '電影', '近日上映大片', '《忍者神龜》[2]真人電影由美國派拉蒙影業(yè)發(fā)行,《洛杉磯之戰(zhàn)》導(dǎo)演喬納森·里貝斯曼執(zhí)導(dǎo)历筝。 \r\n片中四只神龜和老鼠老師都基于漫畫和卡通重新繪制酗昼,由動(dòng)作捕捉技術(shù)實(shí)現(xiàn)。\r\n其中皮特·普勞澤克飾演達(dá)芬奇(武器:武士刀)梳猪,諾爾·費(fèi)舍飾演米開朗基羅(武器:雙節(jié)棍)麻削,阿倫·瑞奇森飾演拉斐爾(武器:鐵叉)蒸痹,杰瑞米·霍華德飾演多拉泰羅(武器:武士棍)。\r\n該片計(jì)劃于2014年8月8日在北美上映呛哟。');
INSERT INTO `message` VALUES (6, '彩票', '中獎(jiǎng)號(hào)碼', '查啥呀查叠荠,你不會(huì)中獎(jiǎng)的!');
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>
這個(gè)配置文件,需要一個(gè)對(duì)象跟數(shù)據(jù)庫交互,這個(gè)對(duì)象是sqlsession,下面講述sqlsession.
二.Sqlsession對(duì)象
Sqlsession的作用:
- 向sql 語句傳入?yún)?shù)
- 執(zhí)行 sql語句
- 獲取執(zhí)行sql語句的結(jié)果
- 事物的控制
如何獲取Sqlsession:
- 通過獲取配置文件獲取數(shù)據(jù)庫連接相關(guān)信息
- 通過配置信息構(gòu)建 sqlSessionFactory 的對(duì)象
- 通過sqlsessionFactory大家數(shù)據(jù)庫會(huì)話鳖孤。
public SqlSession getSqlSession() throws IOException {
// 通過配置文件獲取數(shù)據(jù)庫連接信息
Reader reader = Resources.getResourceAsReader("com/forzp/config/Configuration.xml");
// 通過配置信息構(gòu)建一個(gè)SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
// 通過sqlSessionFactory打開一個(gè)數(shù)據(jù)庫會(huì)話
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 !"".equals(command.trim())">
and COMMAND=#{command}
</if>
<if test="description != null and !"".equals(description.trim())">
and DESCRIPTION like '%' #{description} '%'
</if>
</where>
</select>
其中使用到了ONGL表達(dá)式:
在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動(dòng)態(tài)調(diào)試SQL
由于mybatis的sql語句寫在了xml中苏揣,導(dǎo)致調(diào)試比較困難黄鳍,不能打斷點(diǎn)。這時(shí)需要日志去調(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的級(jí)別:
log.debug
log.info
log.warm
log.error
級(jí)別從小到大框沟,也就是og4j.rootLogger=DEBUG;可以輸出所有的日志類型吐葱;og4j.rootLogger=info 街望,只能夠輸出 info,warm ,error
要想mybtis 顯示日志,必須log4j.rootLogger=DEBUG弟跑;
項(xiàng)目中配置了log4j灾前,mybatis 會(huì)自動(dòng)應(yīng)用log4j
四、一些其他的知識(shí)點(diǎn)
mybatis sql配置文件常用的標(biāo)簽如下:
mapper文件下的標(biāo)簽含義:
nameSpace 標(biāo)簽區(qū)分可以用來區(qū)分sql文件
parameterType 將會(huì)傳入這條語句的參數(shù)類的完全限定名或別名孟辑。這個(gè)屬性是可選的哎甲,因?yàn)?MyBatis 可以通過 TypeHandler 推斷出具體傳入語句的參數(shù),默認(rèn)值為 unset饲嗽。
resultMap 外部 resultMap 的命名引用炭玫。結(jié)果集的映射是 MyBatis 最強(qiáng)大的特性,對(duì)其有一個(gè)很好的理解的話貌虾,許多復(fù)雜映射的情形都能迎刃而解吞加。使用 resultMap 或 resultType,但不能同時(shí)使用尽狠。
五衔憨、一對(duì)多sql xml的配置
java實(shí)體內(nèi)Command包含了一個(gè)List<CommandContent> contentList集合。
public class Command {
/**
* 主鍵
*/
private String id;
/**
* 指令名稱
*/
private String name;
/**
* 描述
*/
private String description;
/**
* 一條指令對(duì)應(yīng)的自動(dò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 !"".equals(name.trim())">
and a.NAME=#{name}
</if>
<if test="description != null and !"".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中的屬性。
六.取自增長(zhǎng) 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的所有知識(shí)都可以在官網(wǎng)上都有德崭,建議看十遍,……_揖盘,地址:http://www.mybatis.org/mybatis-3/zh/configuration.html
關(guān)注我: