使用MyBatis有一個月的時間了,針對自己使用過程中遇到的問題,總結了一些使用方法,具體mybatis的安裝整合使用過程,可以去看一下博主shu_lin的SSM框架搭建博文http://blog.csdn.net/zhshulin/article/details/37956105,相對來說,他的例子是很簡單易懂的,我看過他的博文以後,很簡單就搭建了一個框架處理,這樣就可以開心的使用mybatis了,全部按照他的方法做有時會有問題,比如我就遇到了,不過具體問題具體解決,這個就看具體情況了。
1.MyBatis介紹
MyBatis是一個支持普通SQL查詢,存儲過程和高級映射的優秀持久層框架。MyBatis消除了幾乎所有的JDBC代碼和參數的手工設置以及對結果集的檢索封裝。MyBatis可以使用簡單的XML或註解用於配置和原始映射,將接口和Java的POJO(Plain Old Java Objects,普通的Java對象)映射成數據庫中的記錄。(這段話是從網上摘來的)
2.MyBatis的簡單使用
mybatis的xml文件是可以自動生成的,上面的博文中有介紹,這裏不多說了,先來看下自動生成的結果
首先看一下數據表:
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_name` varchar(255) NOT NULL DEFAULT 'null',
`sex` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8
對應分別生成了model、IDao、xml:
model:
package com.model;
public class User {
private Integer id;
private String userName;
private Integer sex;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
IDao,我這裏叫做對應Mapper接口:
package com.mapper;
import com.model.User;
public interface UserMapper {
int deleteByPrimaryKey(Integer id);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
}
對應的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 namespace="com.mapper.UserMapper" >
<resultMap id="BaseResultMap" type="com.model.User" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="user_name" property="userName" jdbcType="VARCHAR" />
<result column="sex" property="sex" jdbcType="INTEGER" />
</resultMap>
<sql id="Base_Column_List" >
id, user_name, sex
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
from user
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
delete from user
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.model.User" >
insert into user (id, user_name, sex,
truename)
values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{sex,jdbcType=INTEGER})
</insert>
<insert id="insertSelective" parameterType="com.model.User" >
insert into user
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" >
id,
</if>
<if test="userName != null" >
user_name,
</if>
<if test="sex != null" >
sex,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="id != null" >
#{id,jdbcType=INTEGER},
</if>
<if test="userName != null" >
#{user_name,jdbcType=VARCHAR},
</if>
<if test="sex != null" >
#{sex,jdbcType=INTEGER},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.model.User" >
update user
<set >
<if test="user_name != null" >
user_name = #{userName,jdbcType=VARCHAR},
</if>
<if test="sex != null" >
sex = #{sex,jdbcType=INTEGER},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.model.User" >
update user
set user_name = #{userName,jdbcType=VARCHAR},
sex = #{sex,jdbcType=INTEGER},
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>
操作時,主要針對xml文件的修改,裏面大部分是mysql的原生語句(這裏數據庫使用的是mysql,可以選擇不同的數據庫)
我們不能完全依靠自動生成的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" >
<!-- mybatis對應頭部 -->
<!-- namespace爲對應Dao的全限定名 -->
<mapper namespace="com.Dao.UserIDao" >
<!-- resultMap爲返回類型,type爲對於model的全限定名 -->
<resultMap id="BaseResultMap" type="com.model.User">
<!-- result 中 column 爲對於數據庫數據表中一個字段 property 對應實現類中一個變量 jdbcType 對應java中的類型 -->
<id column="id" property="id" jdbcType="INTEGER" />
<result column="user_name" property="user_name" jdbcType="VARCHAR" />
<result column="sex" property="sex" jdbcType="INTEGER" />
</resultMap>
向mybatis傳入數值:
第一種可以直接在對應的dao中使用參數:
<select id="selectByUid" resultMap="BaseResultMap">
<!-- 第一種可以直接在對應的dao中使用參數 -->
<!-- 如:selectByUid(id,user_name,sex); 對於可以使用如下接收 -->
select *
from user
where id = #{0,jdbcType=INTEGER} and user_name = #{1,jdbcType=VARCHAR} and sex = #{2,jdbcType=INTEGER}
</select>
但是數字表示的參數往往讓人看不懂具體含義,所以還有更方便的辦法:
<select id="selectByUid" resultMap="BaseResultMap">
<!-- 這樣使用更佳清晰直觀 -->
<!-- 如:selectByUid(@Param("id")int id,@Param("userName")String userName,@Param("sex")int sex); 對於可以使用如下接收 -->
select *
from user
where id = #{id,jdbcType=INTEGER} and user_name = #{userName,jdbcType=VARCHAR} and sex = #{sex,jdbcType=INTEGER}
</select>
<selecte id="updateByUid" resultMap="BaseResultMap" parameterType="com.model.User">
<!-- 第二種,利用paramterType傳入,parameterType可以是對應model,也可以是java的類型,或者map和list -->
<!-- 如對應model爲上述resultMap -->
select *
from user
where id = #{id,jdbcType=INTEGER} and user_name = #{user_name,jdbcType=VARCHAR} and sex = #{sex,jdbcType=INTEGER}
</select>
<selecte id="updateByUid" resultMap="BaseResultMap" parameterType="java.lang.Integer">
<!-- 使用java的類型 -->
<!-- 如:selectByUid(int); 對於可以使用如下接收 -->
select *
from user
where id = #{id,jdbcType=INTEGER}
</select>
<insert id="insertUserList" parameterType="ArrayList">
<!-- 使用list傳入參數批量插入 -->
<!-- 如:selectByUid(list); 其中list需要分別對於每個字段有屬性,可以使用如下接收 -->
insert into user (id,user_name,sex) values
<foreach collection="list" item="item" index="index" open="" separator="," close="">
<!-- foreach爲迭代標籤,屬性主要有 item,index,collection,open,separator,close -->
(#{item.id,jdbcType=INTEGER},
#{item.user_name,jdbcType=TIMESTAMP},
#{item.sex,jdbcType=TINYINT})
</foreach>
</insert>
foreach爲迭代標籤,屬性主要有 item,index,collection,open,separator,close
item表示集合中每一個元素進行迭代時的別名.
index指定一個名字,用於表示在迭代過程中,每次迭代到的位置
open表示該語句以什麼開始
separator表示迭代之間的分隔符
close表示以什麼結束
從mybatis中返回結果:
第一種,通常爲BaseResultMap,即上面定義的BaseResultMap,使用resultMap返回:
<select id="selectByUid" resultMap="BaseResultMap">
<!-- 第一種,通常爲BaseResultMap,即上面定義的BaseResultMap,使用resultMap返回 -->
select *
from user
where id = #{0,jdbcType=INTEGER}
</select>
第二種,也可以爲對於的java類型,使用resultType返回,查詢結果需對應返回類型:
<select id="selectByUid" resultType="java.lang.Integer">
<!-- 第二種,也可以爲對於的java類型,使用resultType返回,查詢結果需對應返回類型 -->
select id
from user
where id = #{0,jdbcType=INTEGER}
<!-- 對應IDao中使用int selectByUid()接收即可 -->
</select>
<select id="selectUidList" resultType="java.lang.Integer">
<!-- 返回list,同樣是使用resultType返回,這裏不能指定返回類型爲list,而是單個參數對應的可續 -->
select id
from user
<!-- 對應IDao中直接使List<Integer> selectUidList()接收即可 -->
</select>
其他相關內容:
mybatis中insert操作時返回主鍵ID的配置:
<selecte id="insert" parameterType="com.model.User" keyProperty="userId" useGeneratedKeys="true" >
keyProperty表示返回的id要保存到對象對應的哪個屬性中,useGeneratedKeys爲true表示主鍵id爲自增長模式,這裏必須保證id爲自增長模式
xml中可使用的標籤<where> <if> <trim> 以及上面介紹過的<foreach>
<!-- xml中可使用的標籤<where> <if> -->
<selecte id="updateByUid" resultMap="BaseResultMap" parameterType="com.model.User">
<!-- mybatis的xml文件中,可以使用if標籤來做判斷 -->
<!-- 當不確定有條件時,可以使用where標籤,set標籤與where標籤類似 -->
select *
from user
<where>
<if test="id != null">
<!-- if標籤中通常爲比較,用<![CDATA{****}]>進行包裹 -->
<![CDATA[
and id = #{id,jdbcType=INTEGER}
]]>
</if>
<if test="user_name != null">
<![CDATA[
and user_name = #{user_name,jdbcType=VARCHAR}
]]>
</if>
<if test="sex != null">
<![CDATA[
and sex = #{sex,jdbcType=INTEGER}
]]>
</if>
</where>
</select>
<!-- xml中可使用的標籤<trim> -->
<insert id="insertSelective" parameterType="com.model.User">
<!-- mybatis的xml文件中,可以使用if標籤來做判斷,當所有條件都不確定是,可以使用where標籤 -->
insert into user
<trim prefix="(" suffix=")" suffixOverrides="," >
<!-- trim在對於空屬性時使用,利用prefix和suffix添加前後綴,利用suffixOverrides取出多餘的"," -->
<if test="id != null">
id,
</if>
<if test="user_name != null">
user_name,
</if>
<if test="sex != null">
sex,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="id != null">
#{id,jdbcType=INTEGER}
</if>
<if test="user_name != null">
#{user_name,jdbcType=INTEGER}
</if>
<if test="sex != null">
#{sex,jdbcType=INTEGER}
</if>
</trim>
</insert>
xml中可使用"<,>"號時不宜直接使用,容易報錯,可以使用轉義字符進行代替,也可以使用<![CDATA{****}]>進行包裹 :
<selecte id="updateByUid" resultMap="BaseResultMap" parameterType="com.model.User">
<!-- 可以使用轉義字符進行代替,也可以使用<![CDATA{****}]>進行包裹 -->
select *
from user
where id < #{id,jdbcType=INTEGER}
</select>
小於號" < ": <
大於號">": >
和" & ": &
單引號" ' ": '
雙引號" " ": "