mybaits 框架运用
支持普通 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 框架运用的更多相关文章
- MyBaits框架入门总结
MBaits简介 联系方式:18873247271(微信同步) 廖先生 qq:1727292697 MyBatis的前身叫iBatis,本是apache的一个开源项目, 2010年这个项目由apach ...
- OSGI企业应用开发(八)整合Spring和Mybatis框架(一)
到目前为止,我们已经学习了如何使用Blueprint將Spring框架整合到OSGI应用中,并学习了Blueprint&Gemini Blueprint的一些使用细节.本篇文章开始,我们將My ...
- MyBatis_01 框架
Mybatis概述 Mybatis是什么 Mybatis是一个持久层框架. Mybatis的作用 Mybatis是一个持久层框架,当然作用就是操作数据库的(增删改查). 为什么需要学习Myba ...
- 深入学习Mybatis框架(一)- 入门
1.什么是Mybatis? Mybatis是一个优秀持久层框架,提供了对数据库的一系列操作(增删改查).Mybatis可以避免重复的写JDBC代码,让我们以较少的代码实现对数据库的操作,从而提高开发效 ...
- JavaEE MyBatis
1. 简介 MyBatis本是apache的一个开源项目iBatis的升级版,2013年11月迁移到Github,是三层架构中持久层框架. 目前提供了Java..NET.以及Ruby三种语言实现的版 ...
- (原创)mybatis学习二,spring和mybatis的融合
mybatis学习一夯实基础 上文介绍了mybatis的相关知识,这一节主要来介绍mybaits和spring的融合 一,环境搭建 1,jar包下载,下载路径为jar包 2,将包导入到java工程中 ...
- csv格式导出文件
先上传连个图片看看效果,这是界面效果dwz框架(springmvc开发) 点击导出csv效果图 js部分的代码(带条件查询的csv导出): function exportReportCsv(){ ex ...
- JavaWeb日常笔记
1. XML文档的作用和解析 1. XML的基本概述: XML的主要是用来存储一对多的数据,另外还可以用来当做配置文件存储数据.XML的表头如下: <?xml version='1.0' e ...
- Spring Security 入门 (二)
我们在篇(一)中已经谈到了默认的登录页面以及默认的登录账号和密码. 在这一篇中我们将自己定义登录页面及账号密码. 我们先从简单的开始吧:设置自定义的账号和密码(并非从数据库读取),虽然意义不大. 上一 ...
随机推荐
- C#Color对象的使用介绍及颜色对照表
原文地址 http://blog.sina.com.cn/s/blog_3e1177090101bzs3.html 今天用到了特转载 NET框架中的颜色基于4种成份,透明度,红,绿和蓝.每一种成份都 ...
- Python为什么不隐式实现self
Python为什么不隐式实现self Python中类的方法都需要显式的传入一个self占位参数,这让写过C#,Java,PHP,Javascript的我很是不习惯,但是Python这么吊,肯定是有他 ...
- js在控件原有的事件方法中加入自己的方法
有没有碰到过这样的情况,在一个别人的页面上,你想为某个按钮加入自己的控制逻辑,满足条件的情况下才执行原有的事件方法呢? 这个时候在不能修改其原有方法的情况下,先获取控件的事件方法,并将其包装到自己的控 ...
- ssh(sturts2_spring_hibernate) 框架搭建之JPA代替hibernate
一.JPA用来替代hibernate ⒈JPA的全称是JAVA Persistence API.指的是JPA通过注解或者是XML描述对象—关系表的映射关系,并且将运行的实体对象持久化数据库中. ⒉JP ...
- JS面向对象逆向学习法,让难理解的统统一边去(1)~
对于面向对象我只能说呵呵了,为什么呢,因为没对象--- 既然你看到了这里,说明你有一定的基础,虽然本系列文章并不会过多的讲述基础部分,请做好心理准备. 本篇比较简单,这篇文章的意义是让你明白学习面向对 ...
- office2010里怎么设置页码为第几页共几页
在office2010里设置页眉,页脚,页码是很方便的,页眉页脚可以方便的添加信息,统一文本格式,页码的添加可以让读者清楚的知道阅读的进度,也可以方便下次阅读时从相应的页码开始阅读,就像软件中的进度条 ...
- 在使用androidStudio中所遇到的错误
错误如下所示 Error:Execution failed for task ':app:processDebugResources'.> com.android.ide.common.proc ...
- android中出现Error retrieving parent for item: No resource found that matches the Theme.AppCompat.Light
styles.xml中<style name="AppBaseTheme" parent="Theme.AppCompat.Light">提示如下错 ...
- 测试servlet学习笔记
操作方法: 1.新建工程: File——>new——>Java Project——>TestServlet(工程名称)——>Finish. 2.加载servlet-api.ja ...
- Trie树的应用:查询IP地址的ISP
1. 问题描述 给定一个IP地址,如何查询其所属的ISP,如:中国移动(ChinaMobile),中国电信(ChinaTelecom),中国铁通(ChinaTietong)?现有ISP的IP地址区段可 ...