Mybatis初学使用方法总结

使用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> 


第二种,利用paramterType传入,parameterType可以是对应model,也可以是java的类型,或者map和list:

  <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 &lt; #{id,jdbcType=INTEGER} 
  </select>

小于号" < ":  &lt;

大于号">": &gt;

和" & ": &amp; 

单引号" ' ": &apos;

双引号" " ": &quot;



  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值