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

从 XML 中构建 SqlSessionFactory

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

mybatis.cfg.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  4. <configuration>
  5. <!-- 引入外部properties文件 -->
  6. <properties resource="datasources.properties"/>
  7. <!-- 给我们的JAVABEAN定义别名 -->
  8. <typeAliases>
  9. <!-- 一个一个的告知,很麻烦
  10. <typeAlias type="com.lovo.my.beans.UserBean" alias="UserBean"/>
  11. -->
  12. <!-- 自动扫描包,将包内的所有JAVA类的类名,来作为该类的类别名 -->
  13. <package name="com.lovo.my.beans"></package>
  14. </typeAliases>
  15. <!-- 定义mybatis运行环境,default用于设置默认环境 -->
  16. <environments default="development">
  17. <environment id="development">
  18. <!-- transactionManager主要用于设置事务管理器,mybatis提供了2种事物管理器,
  19. 分别是:JDBC,MANAGED ,JDBC代表是直接使用JDBC的提交或回滚来处理事物
  20. MANAGED 代表使用外部容器,如Spring等容器来操作事物 -->
  21. <transactionManager type="JDBC"></transactionManager>
  22. <!-- mybatis提供了3种数据源类型,分别是:POOLED,UNPOOLED,JNDI
  23. POOLED 支持JDBC数据源连接池
  24. UNPOOLD 不支持数据源连接池
  25. JNDI 支持外部容器连接池 -->
  26. <dataSource type="POOLED">
  27. <property name="driver" value="${jdbc.driver}"></property>
  28. <property name="url" value="${jdbc.url}"></property>
  29. <property name="username" value="${jdbc.name}"></property>
  30. <property name="password" value="${jdbc.password}"></property>
  31. </dataSource>
  32. </environment>
  33. </environments>
  34. <mappers>
  35. <!--
  36. <mapper resource="com/lovo/my/dao/IUserMapper.xml"/>
  37. 把每一个类对应的xml文件注入到mybatis中
  38. -->
  39. <!-- 自动扫描包,告知包内的接口与SQL映射文件 -->
  40. <package name="com.lovo.my.dao"/>
  41. </mappers>
  42. </configuration>

SQL 映射的 XML 文件

  1. cache - 配置给定命名空间的缓存。
  2. cache-ref 从其他命名空间引用缓存配置。
  3. resultMap 最复杂,也是最有力量的元素,用来描述如何从数据库结果集中来加载你的对象。
  4. sql 可以重用的 SQL 块,也可以被其他语句引用。
  5. insert 映射插入语句
  6. update 映射更新语句
  7. delete 映射删除语句
  8. select 映射查询语句
  9. 各种语句中的参数含义:
  10. parameterType 方法中传入参数的类型 如入java类,list map
  11. parameterMap
  12. resultMap 返回结果集 一般都是 resultMapid 如下面最近例子 就是userMap
  13. resultType 就表示将查询结果封装成某一个类的对象返回
  14. <sql id="item"> 定义一个可能重复用到的sql字段等
  15. <include refid="item"/> 引入 定义的sql语句
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <mapper namespace="com.lovo.my.dao.IUserMapper">
  5. <!-- 自定义映射关系 -->
  6. <resultMap id="userMap" type="UserBean">
  7. <result property="id" column="id" javaType="java.lang.Integer"/>
  8. <result property="userName" column="user_name" javaType="java.lang.String"/>
  9. <result property="password" column="password" javaType="java.lang.String"/>
  10. <result property="salary" column="salary" javaType="java.lang.Double"/>
  11. </resultMap>
  12. <!-- insert 编写一个新增方法 -->
  13. <insert id="saveUserBean" parameterType="UserBean" useGeneratedKeys="true" keyProperty="u.id">
  14. insert into t_user (user_name,password,sex,salary) values (#{u.userName},#{u.password},#{u.sex},#{u.salary})
  15. </insert>
  16. <insert id="batchAddUserBean" parameterType="java.util.List">
  17. insert into t_user (user_name,password,sex,salary) values
  18. <foreach collection="list" item="user" separator=",">
  19. (#{user.userName},#{user.password},#{user.sex},#{user.salary})
  20. </foreach>
  21. </insert>
  22. <!-- update 编写一个修改方法,在方法中,除了Id属性是必填以外,其他属性均可不填 -->
  23. <update id="updateUserBean">
  24. update t_user set user_name = #{u.userName},password=#{u.password},sex=#{u.sex},salary=#{u.salary} where id= #{id}
  25. </update>
  26. <delete id="deleteUserBean">
  27. delete from t_user where id = #{id}
  28. </delete>
  29. <!-- 批量删除的语法是: delete from t_user id in (,,,,) -->
  30. <delete id="batchDeleteUserBean">
  31. delete from t_user where id in
  32. <foreach collection="list" item="id" separator="," open="(" close=")">
  33. #{id}
  34. </foreach>
  35. </delete>
  36. <select id="getUserBeanByNameAndPassword" resultMap="userMap">
  37. select * from t_user where user_name = #{userName} and password = #{password}
  38. </select>
  39. <select id="findAllUserBean" resultMap="userMap">
  40. select * from t_user
  41. </select>
  42. <select id="selectCountUserBeanByCondition" resultType="int">
  43. select count(*) from t_user where 1=1
  44. <!-- <if test="userName != null and userName != ''">
  45. and user_name like '%${userName}%'
  46. </if>
  47. <if test ="sex != null and sex != ''">
  48. and sex = #{sex}
  49. </if> -->
  50. <include refid="item"/>
  51. </select>
  52. <select id="selectUserBeanByCondition" resultMap="userMap">
  53. select * from t_user where 1=1
  54. <!-- <if test="userName != null and userName != ''">
  55. and user_name like '%${userName}%'
  56. </if>
  57. <if test ="sex != null and sex != ''">
  58. and sex = #{sex}
  59. </if> -->
  60. <include refid="item"/>
  61. limit ${index},${rows}
  62. </select>
  63. <sql id="item">
  64. <if test="userName != null and userName != ''">
  65. and user_name like '%${userName}%'
  66. </if>
  67. <if test ="sex != null and sex != ''">
  68. and sex = #{sex}
  69. </if>
  70. </sql>
  71. </mapper>

one2one

关联查询 方式一

  1. <resultMap id="wifeAndHusbandMap" type="WifeBean">
  2. <result property="id" column="id" javaType="java.lang.Integer"/>
  3. <result property="wifeName" column="wife" javaType="java.lang.String"/>
  4. <association property="husband" javaType="HusbandBean">
  5. <result property="id" column="hid" javaType="java.lang.Integer"/>
  6. <result property="husbandName" column="hhusband" javaType="java.lang.String"/>
  7. </association>
  8. </resultMap>
  9. <select id="queryWifeAndHusband" resultMap="wifeAndHusbandMap">
  10. 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}
  11. </select>

关联查询 方式二

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

one2many

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <mapper namespace="com.even.mapper.one2many.ILockMapper">
  5. <resultMap type="LockBean" id="LockIncludeKeysMap">
  6. <result property="id" column="id"/>
  7. <result property="lockName" column="lock_name"/>
  8. <collection property="keys" column="id" select="com.even.mapper.one2many.IKeyMapper.findByLockId"></collection>
  9. </resultMap>
  10. <insert id="save">
  11. insert into t_lock(lock_name) values(#{lock.lockName})
  12. </insert>
  13. <select id="findById" resultType="LockBean">
  14. select id,lock_name as lockName from t_lock where id = #{id}
  15. </select>
  16. <select id="findByIdIncludeKeys" resultMap="LockIncludeKeysMap">
  17. select id,lock_name from t_lock where id = #{id}
  18. </select>
  19. </mapper>
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <mapper namespace="com.even.mapper.one2many.IKeyMapper">
  5. <resultMap type="KeyBean" id="KeyIncludeLockMap">
  6. <result property="id" column="id"/>
  7. <result property="keyName" column="key_name"/>
  8. <association property="lock" column="fk_lock_id" select="com.even.mapper.one2many.ILockMapper.findById"></association>
  9. </resultMap>
  10. <insert id="batchSave">
  11. insert into t_key(key_name,fk_lock_id) values
  12. <foreach collection="list" item="key" separator=",">
  13. (#{key.keyName},#{key.lock.id})
  14. </foreach>
  15. </insert>
  16. <select id="findByIdIncludeLock" resultMap="KeyIncludeLockMap">
  17. select id,key_name,fk_lock_id from t_key where id = #{id}
  18. </select>
  19. </mapper>

many2many

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <mapper namespace="com.even.mapper.many2many.IStudentMapper">
  5. <resultMap type="StudentBean" id="StudentMap">
  6. <result property="id" column="id"/>
  7. <result property="studentName" column="student_name"/>
  8. <result property="sex" column="sex"/>
  9. <result property="age" column="age"/>
  10. <collection property="courses" column="id" select="findCourseByStudentId"></collection>
  11. </resultMap>
  12. <select id="findByIdIncludeCourses" resultMap="StudentMap">
  13. select id,student_name,sex,age from t_student where id = #{id}
  14. </select>
  15. <select id="findCourseByStudentId" resultType="CourseBean">
  16. 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})
  17. </select>
  18. </mapper>
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <mapper namespace="com.even.mapper.many2many.ICourseMapper">
  5. <resultMap type="CourseBean" id="CourseMap">
  6. <result property="id" column="id"/>
  7. <result property="courseName" column="course_name"/>
  8. <collection property="students" column="id" select="findStudentByCourseId"></collection>
  9. </resultMap>
  10. <select id="findByIdIncludeStudents" resultMap="CourseMap">
  11. select id,course_name from t_course where id = #{id}
  12. </select>
  13. <select id="findStudentByCourseId" resultType="StudentBean">
  14. 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})
  15. </select>
  16. </mapper>
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <mapper namespace="com.even.mapper.many2many.IStudentCourseMapper">
  5. <insert id="choiceCourse">
  6. insert into t_student_course(fk_student_id,fk_course_id) values
  7. <foreach collection="list" item="sc" separator=",">
  8. (#{sc.studentBean.id},#{sc.courseBean.id})
  9. </foreach>
  10. </insert>
  11. </mapper>
  1. 在没封装的情况下测试类需要这么写
  2. package me.gacl.test;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.Reader;
  6. import me.gacl.domain.User;
  7. import org.apache.ibatis.io.Resources;
  8. import org.apache.ibatis.session.SqlSession;
  9. import org.apache.ibatis.session.SqlSessionFactory;
  10. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  11. public class Test1 {
  12. public static void main(String[] args) throws IOException {
  13. //mybatis的配置文件
  14. String resource = "conf.xml";
  15. //使用类加载器加载mybatis的配置文件(它也加载关联的映射文件)
  16. InputStream is = Test1.class.getClassLoader().getResourceAsStream(resource);
  17. //构建sqlSession的工厂
  18. SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
  19. //使用MyBatis提供的Resources类加载mybatis的配置文件(它也加载关联的映射文件)
  20. //Reader reader = Resources.getResourceAsReader(resource);
  21. //构建sqlSession的工厂
  22. //SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
  23. //创建能执行映射文件中sql的sqlSession
  24. SqlSession session = sessionFactory.openSession();
  25. /**
  26. * 映射sql的标识字符串,
  27. * me.gacl.mapping.userMapper是userMapper.xml文件中mapper标签的namespace属性的值,
  28. * getUser是select标签的id属性值,通过select标签的id属性值就可以找到要执行的SQL
  29. */
  30. String statement = "me.gacl.mapping.userMapper.getUser";//映射sql的标识字符串
  31. //执行查询返回一个唯一user对象的sql
  32. User user = session.selectOne(statement, 1);
  33. System.out.println(user);
  34. }
  35. }

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. iOS Crash常规跟踪方法及Bugly集成运用

    当app出现崩溃, 研发阶段一般可以通过以下方式来跟踪crash信息 #1.模拟器运行, 查看xcode错误日志 #2.真机调试, 查看xcode错误日志 #3.真机运行, 查看device系统日志 ...

  2. 缓存篇~第七回 Redis实现基于方法签名的数据集缓存(可控更新,分布式数据缓存)

    返回目录 本篇文章可以说是第六回 Microsoft.Practices.EnterpriseLibrary.Caching实现基于方法签名的数据集缓存(可控更新,WEB端数据缓存)的续篇,事实上,有 ...

  3. 爱上MVC~MVC4模型验证可以放在前端

    回到目录 MVC4.0推出后,在模型验证上有了一个新的改近,它支持前端验证,即在用户POST之前,如果验证失败,则Action(POST方式的)不会被执行,而直接停留在原视图,这对于用户体验是好的,它 ...

  4. 学习ASP.NET MVC(五)——我的第一个ASP.NET MVC CURD页面

    在上一篇文章中我们已经创建了实体类,在这一篇文章中,我将创建一个新的控制器类——BookController,使用BookController对Books表中的数据进行CURD操作的方法,并使用视图模 ...

  5. javascript_core_03之数组

    1.数组:连续存储多个数据,一组连续变量的集合: ①创建空数组:var arr=[]:或者var arr=new Array(): ②创建初始化数组:var arr=[值1,值2,……]:或者var ...

  6. ASP.NET MVC在线人数统计

    在Global.asax.cs文件中代码: protected void Application_Start() { Application[; AreaRegistration.RegisterAl ...

  7. Topology and Geometry in OpenCascade-Vertex

    Topology and Geometry in OpenCascade-Vertex eryar@163.com 摘要Abstract:本文简要介绍了几何造型中的边界表示法(BRep),并结合程序说 ...

  8. Android开发之注册登录

    昨天给大家介绍了一下关于Android端向服务器端发送数据的方法,不过貌似有一点瑕疵,今天经过调试已经解决,在这里给大家介绍一下 貌似Android4.0以后版本的对于网络权限要求变得严格,导致昨天编 ...

  9. [OpenCV] Samples 07: create_mask

    鼠标画线,圈地,构造相关mask图片(黑白). 支持鼠标左键右键中间键点击事件. /* * create_mask.cpp * * Author: * Siddharth Kherada <si ...

  10. php基础教程-数据类型

    PHP 支持八种原始类型(type). 四种标量类型: string(字符串) integer(整型) float(浮点型,也作 double ) boolean(布尔型) 两种复合类型: array ...