支持普通 SQL 查询,存储过程和高级映射的ORM持久层框架。以一 个 SqlSessionFactory 对象的实例为核心。

从 XML 中构建 SqlSessionFactory

configuration 配置
properties 属性
settings 设置
typeAliases 类型命名
typeHandlers 类型处理器
objectFactory 对象工厂
plugins 插件
environments 环境
environment 环境变量
transactionManager 事务管理器
dataSource 数据源
映射器
String resource = "org/mybatis/example/Configuration.xml";
Reader reader = Resources.getResourceAsReader(resource);
sqlMapper = new SqlSessionFactoryBuilder().build(reader);

mybatis.cfg.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>
<!-- 引入外部properties文件 -->
<properties resource="datasources.properties"/> <!-- 给我们的JAVABEAN定义别名 -->
<typeAliases>
<!-- 一个一个的告知,很麻烦
<typeAlias type="com.lovo.my.beans.UserBean" alias="UserBean"/>
-->
<!-- 自动扫描包,将包内的所有JAVA类的类名,来作为该类的类别名 -->
<package name="com.lovo.my.beans"></package>
</typeAliases> <!-- 定义mybatis运行环境,default用于设置默认环境 -->
<environments default="development">
<environment id="development">
<!-- transactionManager主要用于设置事务管理器,mybatis提供了2种事物管理器,
分别是:JDBC,MANAGED ,JDBC代表是直接使用JDBC的提交或回滚来处理事物
MANAGED 代表使用外部容器,如Spring等容器来操作事物 -->
<transactionManager type="JDBC"></transactionManager>
<!-- mybatis提供了3种数据源类型,分别是:POOLED,UNPOOLED,JNDI
POOLED 支持JDBC数据源连接池
UNPOOLD 不支持数据源连接池
JNDI 支持外部容器连接池 -->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.name}"></property>
<property name="password" value="${jdbc.password}"></property>
</dataSource>
</environment>
</environments> <mappers>
<!--
<mapper resource="com/lovo/my/dao/IUserMapper.xml"/>
把每一个类对应的xml文件注入到mybatis中
-->
<!-- 自动扫描包,告知包内的接口与SQL映射文件 -->
<package name="com.lovo.my.dao"/>
</mappers> </configuration>

SQL 映射的 XML 文件

cache - 配置给定命名空间的缓存。
cache-ref – 从其他命名空间引用缓存配置。
resultMap – 最复杂,也是最有力量的元素,用来描述如何从数据库结果集中来加载你的对象。
sql – 可以重用的 SQL 块,也可以被其他语句引用。
insert – 映射插入语句
update – 映射更新语句
delete – 映射删除语句
select – 映射查询语句
各种语句中的参数含义:
parameterType 方法中传入参数的类型 如入java类,list ,map 等
parameterMap
resultMap 返回结果集 一般都是 resultMap的id; 如下面最近例子 就是userMap
resultType 就表示将查询结果封装成某一个类的对象返回
<sql id="item"> 定义一个可能重复用到的sql字段等
<include refid="item"/> 引入 定义的sql语句
<?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.lovo.my.dao.IUserMapper"> <!-- 自定义映射关系 -->
<resultMap id="userMap" type="UserBean">
<result property="id" column="id" javaType="java.lang.Integer"/>
<result property="userName" column="user_name" javaType="java.lang.String"/>
<result property="password" column="password" javaType="java.lang.String"/>
<result property="salary" column="salary" javaType="java.lang.Double"/>
</resultMap> <!-- insert 编写一个新增方法 -->
<insert id="saveUserBean" parameterType="UserBean" useGeneratedKeys="true" keyProperty="u.id">
insert into t_user (user_name,password,sex,salary) values (#{u.userName},#{u.password},#{u.sex},#{u.salary})
</insert> <insert id="batchAddUserBean" parameterType="java.util.List">
insert into t_user (user_name,password,sex,salary) values
<foreach collection="list" item="user" separator=",">
(#{user.userName},#{user.password},#{user.sex},#{user.salary})
</foreach>
</insert> <!-- update 编写一个修改方法,在方法中,除了Id属性是必填以外,其他属性均可不填 -->
<update id="updateUserBean">
update t_user set user_name = #{u.userName},password=#{u.password},sex=#{u.sex},salary=#{u.salary} where id= #{id}
</update> <delete id="deleteUserBean">
delete from t_user where id = #{id}
</delete> <!-- 批量删除的语法是: delete from t_user id in (,,,,) -->
<delete id="batchDeleteUserBean">
delete from t_user where id in
<foreach collection="list" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</delete> <select id="getUserBeanByNameAndPassword" resultMap="userMap">
select * from t_user where user_name = #{userName} and password = #{password}
</select> <select id="findAllUserBean" resultMap="userMap">
select * from t_user
</select> <select id="selectCountUserBeanByCondition" resultType="int">
select count(*) from t_user where 1=1
<!-- <if test="userName != null and userName != ''">
and user_name like '%${userName}%'
</if> <if test ="sex != null and sex != ''">
and sex = #{sex}
</if> --> <include refid="item"/>
</select> <select id="selectUserBeanByCondition" resultMap="userMap">
select * from t_user where 1=1
<!-- <if test="userName != null and userName != ''">
and user_name like '%${userName}%'
</if> <if test ="sex != null and sex != ''">
and sex = #{sex}
</if> --> <include refid="item"/>
limit ${index},${rows}
</select> <sql id="item">
<if test="userName != null and userName != ''">
and user_name like '%${userName}%'
</if> <if test ="sex != null and sex != ''">
and sex = #{sex}
</if>
</sql> </mapper>

one2one

关联查询 方式一

  <resultMap id="wifeAndHusbandMap" type="WifeBean">
<result property="id" column="id" javaType="java.lang.Integer"/>
<result property="wifeName" column="wife" javaType="java.lang.String"/> <association property="husband" javaType="HusbandBean">
<result property="id" column="hid" javaType="java.lang.Integer"/>
<result property="husbandName" column="hhusband" javaType="java.lang.String"/>
</association>
</resultMap> <select id="queryWifeAndHusband" resultMap="wifeAndHusbandMap">
select w.id as wid,w.wife as wwife,h.id as hid,h.husband as hhusband from t_wife as w,t_husband as h where h.id = w.fk_husband_id and w.id = #{id}
</select>

关联查询 方式二

   <resultMap id="wifeAndHusbandMap" type="WifeBean">
<result property="id" column="id" javaType="java.lang.Integer"/>
<result property="wifeName" column="wife" javaType="java.lang.String"/> <!-- 所有的关联查询中,column="" 这一部分,一定是后面方法所需要的 -->
<association property="husband" column="fk_husband_id" select="com.lovo.my.dao.IHusbandMapper.getHusbandBeanById" javaType="HusbandBean"/>
</resultMap> <select id="queryWifeAndHusband" resultMap="wifeAndHusbandMap">
select * from t_wife where id = #{id}
</select>

one2many

<?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.even.mapper.one2many.ILockMapper"> <resultMap type="LockBean" id="LockIncludeKeysMap">
<result property="id" column="id"/>
<result property="lockName" column="lock_name"/>
<collection property="keys" column="id" select="com.even.mapper.one2many.IKeyMapper.findByLockId"></collection>
</resultMap> <insert id="save">
insert into t_lock(lock_name) values(#{lock.lockName})
</insert> <select id="findById" resultType="LockBean">
select id,lock_name as lockName from t_lock where id = #{id}
</select> <select id="findByIdIncludeKeys" resultMap="LockIncludeKeysMap">
select id,lock_name from t_lock where id = #{id}
</select> </mapper>
<?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.even.mapper.one2many.IKeyMapper"> <resultMap type="KeyBean" id="KeyIncludeLockMap">
<result property="id" column="id"/>
<result property="keyName" column="key_name"/>
<association property="lock" column="fk_lock_id" select="com.even.mapper.one2many.ILockMapper.findById"></association>
</resultMap> <insert id="batchSave">
insert into t_key(key_name,fk_lock_id) values
<foreach collection="list" item="key" separator=",">
(#{key.keyName},#{key.lock.id})
</foreach>
</insert> <select id="findByIdIncludeLock" resultMap="KeyIncludeLockMap">
select id,key_name,fk_lock_id from t_key where id = #{id}
</select> </mapper>

many2many

<?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.even.mapper.many2many.IStudentMapper"> <resultMap type="StudentBean" id="StudentMap">
<result property="id" column="id"/>
<result property="studentName" column="student_name"/>
<result property="sex" column="sex"/>
<result property="age" column="age"/>
<collection property="courses" column="id" select="findCourseByStudentId"></collection>
</resultMap> <select id="findByIdIncludeCourses" resultMap="StudentMap">
select id,student_name,sex,age from t_student where id = #{id}
</select> <select id="findCourseByStudentId" resultType="CourseBean">
select id,course_name as courseName from t_course where id in(select fk_course_id from t_student_course where fk_student_id = #{id})
</select> </mapper>
<?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.even.mapper.many2many.ICourseMapper"> <resultMap type="CourseBean" id="CourseMap">
<result property="id" column="id"/>
<result property="courseName" column="course_name"/>
<collection property="students" column="id" select="findStudentByCourseId"></collection>
</resultMap> <select id="findByIdIncludeStudents" resultMap="CourseMap">
select id,course_name from t_course where id = #{id}
</select> <select id="findStudentByCourseId" resultType="StudentBean">
select id,student_name as studentName,sex,age from t_student where id in(select fk_student_id from t_student_course where fk_course_id = #{id})
</select> </mapper>
<?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.even.mapper.many2many.IStudentCourseMapper"> <insert id="choiceCourse">
insert into t_student_course(fk_student_id,fk_course_id) values
<foreach collection="list" item="sc" separator=",">
(#{sc.studentBean.id},#{sc.courseBean.id})
</foreach>
</insert> </mapper>
在没封装的情况下测试类需要这么写
package me.gacl.test; import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import me.gacl.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class Test1 { public static void main(String[] args) throws IOException {
//mybatis的配置文件
String resource = "conf.xml";
//使用类加载器加载mybatis的配置文件(它也加载关联的映射文件)
InputStream is = Test1.class.getClassLoader().getResourceAsStream(resource);
//构建sqlSession的工厂
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
//使用MyBatis提供的Resources类加载mybatis的配置文件(它也加载关联的映射文件)
//Reader reader = Resources.getResourceAsReader(resource);
//构建sqlSession的工厂
//SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
//创建能执行映射文件中sql的sqlSession
SqlSession session = sessionFactory.openSession();
/**
* 映射sql的标识字符串,
* me.gacl.mapping.userMapper是userMapper.xml文件中mapper标签的namespace属性的值,
* getUser是select标签的id属性值,通过select标签的id属性值就可以找到要执行的SQL
*/
String statement = "me.gacl.mapping.userMapper.getUser";//映射sql的标识字符串
//执行查询返回一个唯一user对象的sql
User user = session.selectOne(statement, 1);
System.out.println(user);
}
}

mybaits 框架运用的更多相关文章

  1. MyBaits框架入门总结

    MBaits简介 联系方式:18873247271(微信同步) 廖先生 qq:1727292697 MyBatis的前身叫iBatis,本是apache的一个开源项目, 2010年这个项目由apach ...

  2. OSGI企业应用开发(八)整合Spring和Mybatis框架(一)

    到目前为止,我们已经学习了如何使用Blueprint將Spring框架整合到OSGI应用中,并学习了Blueprint&Gemini Blueprint的一些使用细节.本篇文章开始,我们將My ...

  3. MyBatis_01 框架

    Mybatis概述 Mybatis是什么 Mybatis是一个持久层框架.   Mybatis的作用 Mybatis是一个持久层框架,当然作用就是操作数据库的(增删改查).   为什么需要学习Myba ...

  4. 深入学习Mybatis框架(一)- 入门

    1.什么是Mybatis? Mybatis是一个优秀持久层框架,提供了对数据库的一系列操作(增删改查).Mybatis可以避免重复的写JDBC代码,让我们以较少的代码实现对数据库的操作,从而提高开发效 ...

  5. JavaEE MyBatis

    1.  简介 MyBatis本是apache的一个开源项目iBatis的升级版,2013年11月迁移到Github,是三层架构中持久层框架. 目前提供了Java..NET.以及Ruby三种语言实现的版 ...

  6. (原创)mybatis学习二,spring和mybatis的融合

    mybatis学习一夯实基础 上文介绍了mybatis的相关知识,这一节主要来介绍mybaits和spring的融合 一,环境搭建 1,jar包下载,下载路径为jar包 2,将包导入到java工程中 ...

  7. csv格式导出文件

    先上传连个图片看看效果,这是界面效果dwz框架(springmvc开发) 点击导出csv效果图 js部分的代码(带条件查询的csv导出): function exportReportCsv(){ ex ...

  8. JavaWeb日常笔记

    1.   XML文档的作用和解析 1. XML的基本概述: XML的主要是用来存储一对多的数据,另外还可以用来当做配置文件存储数据.XML的表头如下: <?xml version='1.0' e ...

  9. Spring Security 入门 (二)

    我们在篇(一)中已经谈到了默认的登录页面以及默认的登录账号和密码. 在这一篇中我们将自己定义登录页面及账号密码. 我们先从简单的开始吧:设置自定义的账号和密码(并非从数据库读取),虽然意义不大. 上一 ...

随机推荐

  1. MVVM架构~knockoutjs系列之验证信息自定义输出~再续

    返回目录 对于一个项目的表单验证,方式有很多,效果也有很多,具体使用哪种完成取决于产品这边,产品让你用什么,你就要用什么,而做为开发人员,我们要做的就是"整理近可能多的架构方式",这样才可以自由的应变 ...

  2. MVVM架构~knockoutjs系列之为Ajax传递Ko数组对象

    返回目录 一些要说的 这是一个很有意思的题目,在KO里,有对象和数组对象两种,但这两种对象对外表现都是一个function,如果希望得到他的值,需要进行函数式调用,如ko_a(),它的结果为一个具体值 ...

  3. 题目一:打印出所有的 "水仙花数 ",所谓 "水仙花数 "是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个 "水仙花数 ",因为153=1的三次方+5的三次方+3的三次方。

  4. Linux运维之道(大量经典案例、问题分析,运维案头书,红帽推荐)

    Linux运维之道(大量经典案例.问题分析,运维案头书,红帽推荐) 丁明一 编   ISBN 978-7-121-21877-4 2014年1月出版 定价:69.00元 448页 16开 编辑推荐 1 ...

  5. 每天一个linux命令(20):find命令之exec

    find是我们很常用的一个Linux命令,但是我们一般查找出来的并不仅仅是看看而已,还会有进一步的操作,这个时候exec的作用就显现出来了. exec解释: -exec  参数后面跟的是command ...

  6. KlayGE 4.4中渲染的改进(二):DR的其他改进

    转载请注明出处为KlayGE游戏引擎,本文的永久链接为http://www.klayge.org/?p=2749   上一篇讲了TBDR的实现,本篇继续讲解deferred rendering层的一些 ...

  7. Ubuntu 14.04上安装caffe

    本来实在windows 10上尝试安装caffe,装了一天没装上,放弃; 改在windows上装ubuntu的双系统,装了一个下午,不小心windows的系统盘被锁死了,也不会unlock?只好含泪卸 ...

  8. 30分钟全面解析-图解AJAX原理

    先上原理图: 高清无码图在这里:点我查看大图!!! 背景: 1.传统的Web网站,提交表单,需要重新加载整个页面. 2.如果服务器长时间未能返回Response,则客户端将会无响应,用户体验很差. 3 ...

  9. Android实现下滑和上滑事件

    做过开发的对于下滑刷新与上滑加载都一定不陌生,因为我们在很多时候都会使用到,那对对于这个效果如何实现呢?相信难道过很多小伙伴,今天我就带领大家一道通过第三方组件快速完成上述效果的实现,保准每位小伙伴都 ...

  10. 浅谈AngularJS中的$parse和$eval

    AngularJS的初学者常常会对$parse和$eval两个内建服务感到有些困惑,今天我们就来说说AngularJS中的$parse和$eval. 总的来说,$parse和$eval都是作用于Ang ...