您的位置:首页 > 其它

MyBatis持久层框架使用总结

2016-07-05 23:47 411 查看
MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。

2013年11月迁移到Github,MyBatis的Github地址:https://github.com/mybatis/mybatis-3

iBATIS一词来源于“internet”和“abatis”的组合,是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAO)。

MyBatis 是支持普通 SQL查询,存储过程和高级映射的优秀持久层框架。MyBatis 消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。MyBatis 使用简单的 XML或注解用于配置和原始映射,将接口和 Java 的POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。

每个MyBatis应用程序主要都是使用SqlSessionFactory实例的,一个SqlSessionFactory实例可以通过SqlSessionFactoryBuilder获得。SqlSessionFactoryBuilder可以从一个xml配置文件或者一个预定义的配置类的实例获得。

1.使用Generator自动生成Dao层,Model层和Mapper层。

MyBatis Generator下载地址:http://www.mybatis.org/generator/

MyBatis Generator中文介绍:http://generator.sturgeon.mopaas.com/

以下用mybatis-generator-core-1.3.2.jar插件加jdbc数据库连接包自动导出持久层dao包,model包和mapper包。

需要用到的Java包有:

mybatis-generator-core-1.3.2.jar,

mysql-connector-java-5.1.34.jar,

ojdbc14-10.2.0.1.0.jar,

sqljdbc4-4.0.jar。

配置文件: generator.xml

package com.ouc.mkhl.platform.authority.model;

import java.io.Serializable;

//用户信息
public class User implements Serializable {

private static final long serialVersionUID = 1098321123L;

private Integer id;    //用户Id

private String userName;   //用户名

private String password;    //未加密密码

private String email;    //邮箱

private String trueName;  //真实姓名

private String sex;   //性别

private Integer age;   //年龄

private String telephone;  //手机

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 getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email == null ? null : email.trim();
}

public String getTrueName() {
return trueName;
}

public void setTrueName(String trueName) {
this.trueName = trueName == null ? null : trueName.trim();
}

public String getSex() {
return sex;
}

public void setSex(String sex) {
this.sex = sex == null ? null : sex.trim();
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

public String getTelephone() {
return telephone;
}

public void setTelephone(String telephone) {
this.telephone = telephone == null ? null : telephone.trim();
}

}


View Code

3)增删改查:

(1)select查询:

① id:在这个模式下唯一的标识符,可被其它语句引用。

② parameterType:传给此语句的参数的完整类名或别名。

③ resultType:语句返回值类型的整类名或别名。注意,如果是集合,那么这里填写的是集合的项的整类名或别名,而不是集合本身的类名。(resultType 与resultMap 不能并用)

④ resultMap:引用的外部resultMap名。结果集映射是MyBatis 中最强大的特性。许多复杂的映射都可以轻松解决。(resultType 与resultMap 不能并用)

⑤ flushCache:如果设为true,则会在每次语句调用的时候就会清空缓存。select语句默认设为false。

⑥ useCache:如果设为true,则语句的结果集将被缓存。select语句默认设为false。

⑦ timeout :设置驱动器在抛出异常前等待回应的最长时间,默认为不设值,由驱动器自己决定。

示例:查询所有用户信息:selectUsers

<select id="selectUsers" resultMap="UserBaseResultMap">
select id,userName,email from user
</select>


(2) insert插入:saveUser

此处数据库表使用主键自增,主键为id。

① fetchSize:设置一个值后,驱动器会在结果集数目达到此数值后,激发返回,默认为不设值,由驱动器自己决定。

② statementType:statement,preparedstatement,callablestatement。预准备语句、可调用语句。

③ useGeneratedKeys:使用JDBC的getGeneratedKeys方法来获取数据库自己生成的主键(MySQL、SQLSERVER等关系型数据库会有自动生成的字段)。

④ keyProperty:标识一个将要被MyBatis设置进getGeneratedKeys的key所返回的值,或者为insert语句使用一个selectKey子元素。

<insert id="saveUser" parameterType="User" >
insert into user (userName, password, email, trueName, sex, age, telephone)
values (#{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
#{email,jdbcType=VARCHAR}, #{trueName,jdbcType=VARCHAR},
#{sex,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}, #{telephone,jdbcType=VARCHAR})
</insert>


(3)update更新:动态更新SQL:updateUser

<update id="updateUser" parameterType="User" >
update user
<set >
<if test="userName != null" >
userName = #{userName,jdbcType=VARCHAR},
</if>
<if test="password != null" >
password = #{password,jdbcType=VARCHAR},
</if>
<if test="email != null" >
email = #{email,jdbcType=VARCHAR},
</if>
<if test="trueName != null" >
trueName = #{trueName,jdbcType=VARCHAR},
</if>
<if test="sex != null" >
sex = #{sex,jdbcType=VARCHAR},
</if>
<if test="age != null" >
age = #{age,jdbcType=INTEGER},
</if>
<if test="telephone != null" >
telephone = #{telephone,jdbcType=VARCHAR},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>


(4)delete删除:deleteUser

<delete id="deleteUser" parameterType="Integer">
delete from user
where id = #{id,jdbcType=INTEGER}
</delete>


(5)sql: Sql元素用来定义一个可以复用的SQL语句段,供其它语句调用。

<sql id="UserBaseColumnList" >
userName, password, email, telephone
</sql>
<select id="getUsers" resultMap="UserBaseResultMap">
select
<include refid="UserBaseColumnList" />
from user
</select>


(6)参数:parameters:MyBatis可以使用基本数据类型和Java的复杂数据类型。
基本数据类型,String,int,date等。
使用基本数据类型,只能提供一个参数,所以需要使用Java实体类,或Map类型做参数类型。通过#{}可以直接得到其属性。

① 基本数据类型参数:String

<select id="getUserByName" resultType="User" parameterType="String" >
select id, userName, email  from user
where userName = #{userName,jdbcType=VARCHAR}
</select>


Java代码:

public User getUserByName(String name); // 根据用户名获取用户信息


② Java实体类型参数:User

<insert id="saveUser" parameterType="User" >
insert into user (userName, password, email, trueName, sex, age, telephone)
values (#{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
#{email,jdbcType=VARCHAR}, #{trueName,jdbcType=VARCHAR},
#{sex,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}, #{telephone,jdbcType=VARCHAR})
</insert>


Java代码:

public int saveUser(User user); // 插入用户信息


③ Map参数:Map<String, Object> recordMap

<select id="selectChildGroupTotalNum" resultType="Integer" >
select count(*) from groupinfo
<trim prefix="WHERE" prefixOverrides="AND|OR">
and id in
<foreach collection="idStr" item="ids" open="(" separator="," close=")">
#{ids}
</foreach>
<if test="name!= null and name!='' " >
and name LIKE CONCAT(CONCAT('%', #{name}),'%')
</if>
<if test="description!= null and description!='' " >
AND description LIKE CONCAT(CONCAT('%', #{description}),'%')
</if>
<if test="type != null and type!=-1 " >
AND type = #{type,jdbcType=INTEGER}
</if>
<if test="category != null and category!=-1 " >
AND category = #{category,jdbcType=INTEGER}
</if>
</trim>
</select>


Java代码:

//获取子组总记录数
public int selectChildGroupTotalNum(Map<String, Object> recordMap);


Map<String, Object> recordMap = new HashMap<String, Object>();
recordMap.put("idStr", group.getChildgroupids().split(","));
recordMap.put("name", name);
recordMap.put("description", description);
recordMap.put("type", -1);
recordMap.put("category", -1);
childGroupTotalNum = groupDao.selectChildGroupTotalNum(recordMap);


④ 多参数:

方法一:按顺序传递参数。

<!-- 根据参数名查询参数 -->
<select id="selectSensorNobySensorName" resultType="Integer" useCache="false" flushCache="true">
select SensorNo from sensorconfig
where Name = #{0} and TestunitNo = #{1} and LABCODE = #{2}
</select>


Java代码:

//根据参数名查询参数ID
public int selectSensorNobySensorName(String sensorName, int testUnitNo, String labCode);


方法二:接口参数上添加@Param注解。

<select id="selectByUserNameAndVCode" resultMap="UserBaseResultMap">
select id, userName from user
<trim prefix="WHERE" prefixOverrides="AND|OR">
<if test="userName!= null and userName!='' ">
and userName LIKE CONCAT(CONCAT('%', #{userName}),'%')
</if>
<if test="supplierno!= null and supplierno!='' ">
and supplierNo LIKE CONCAT(CONCAT('%', #{supplierno}),'%')
</if>
and supplierNo != 'test'
</trim>
LIMIT #{startIndex},#{pageSize}
</select>


Java代码:

// 根据用户名和V码查询用户信息
public List<User> selectByUserNameAndVCode(
@Param("userName") String userName,
@Param("supplierno") String supplierno,
@Param("startIndex") int startIndex, @Param("pageSize") int pageSize);


4)动态SQL语句

selectKey标签,if标签,if + where的条件判断,if + set的更新语句,if + trim代替where/set标签,trim代替set,choose (when, otherwise),foreach标签。动态SQL语句算是MyBatis最灵活的部分吧,用好了非常方便。

示例:selectTotalNumByAccountType

<select id="selectTotalNumByAccountType" resultType="Integer" >
select count(*) from user
<trim prefix="WHERE" prefixOverrides="AND|OR">
and id not in
<foreach collection="idStr" item="ids" open="(" separator="," close=")">
#{ids}
</foreach>
<if test="userName!= null and userName!='' ">
and userName LIKE CONCAT(CONCAT('%', #{userName}),'%')
</if>
<if test="supplierno!= null and supplierno!='' ">
and supplierNo LIKE CONCAT(CONCAT('%', #{supplierno}),'%')
</if>
<if test="trueName!= null and trueName!='' ">
and trueName LIKE CONCAT(CONCAT('%', #{trueName}),'%')
</if>
AND accountType = #{accountType}
</trim>
</select>


可以查看的文章:

1. MyBatis学习 之 三、动态SQL语句:/article/4080057.html

2.MyBatis和Hibernate相比,优势在哪里? https://www.zhihu.com/question/21104468
3.【持久化框架】Mybatis简介与原理: /article/1375765.html

4.MyBatis学习总结(一)——MyBatis快速入门: /article/4676521.html

5.利用mybatis-generator自动生成代码: http://www.cnblogs.com/yjmyzz/p/4210554.html

6.MyBatis魔法堂:即学即用篇: /article/4741091.html

7.mybatis 使用经验小结: /article/4607382.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: