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

JDBC –> dbutils(自动封装结果集) –>MyBatis –>Hinernate

简单环境搭建:JDBC Driver相关jar包和Mybatis.jar包。

1.     SqlSessionFactory的构建:

SqlSessionFactory是整个MyBatis框架的核心,其对象实例可以通过SqlSessionFactoryBuilder来获得。创建方法:

1. 通过org.apache.ibatis.io.Resources. getResourceAsStream(“conf.xml”);或者TestMyBatis.class.getClassLoader().getResourceAsStream("conf.xml");或其他方式得到一个InputStream流,然后通过SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputstream);来构建SqlSessionFactory。

3. SqlSession的创建:

SqlSession是以数据为背景的所有执行SQL操作的方法,可以使用SqlSession实例来直接执行已映射的SQL语句。

SqlSession session=factory.openSession();

String statement="com.mybatis.test.userMapper.getUser";

User user=session.selectOne(statement, 1);

session.close();

Conf.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>

    <!--

      <environments default="development">

      <environments default="work">

     -->

    <environments default="development">

           <environment id="development">

               <!--

                transactionManager:在MyBatis中有两种事务管理类型[type=JDBC | MANAGED ]

                * JDBC -这个配置直接简单的使用了JDBC的提交和回滚设置。它依赖于从数据源得到的连接来管理事务范围。

                * MANAGED -这个配置几乎没有做什么,它从来不提交或回滚一个连接。而它会让容器来管理事务的整个生命周期。默认情况下它会关闭连接。如果在一些容器中并不希望这样,那么需要使用closeConnection属性设置为false:例如

                <transactionManager type="MANAGED">

                   <property name="closeConnection" value ="false"/>

                </transactionManager>

                -->

                  <transactionManager type="JDBC"/>

                     <dataSource type="POOLED">

                            <property name="driver" value="com.mysql.jdbc.Driver"/>

                            <property name="url" value="jdbc:mysql://localhost:3306/cdcol"/>

                            <property name="username" value="root"/>

                            <property name="password" value="x5uq4xWjTvUMH23H"/>

                     </dataSource>

           </environment>

    </environments>

    <mappers>

        <mapper resource="com/mybatis/test/userMapper.xml"/>

    </mappers>

</configuration>

userMapper.xml文件:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">

<mapper namespace="com.mybatis.test.userMapper">

    <select id="getUser" parameterType="int" resultType="com.mybatis.test.User">

        select * from users where id=#{id}

    </select>

    <insert id="addUser" parameterType="com.mybatis.test.User">

        insert into users(name,age) values(#{name},#{age})

    </insert>

    <delete id="deleteUser" parameterType="int">

        delete from users where id=#{id}

    </delete>

    <update id="updateUser" parameterType="com.mybatis.test.User">

        update users set name=#{name},age=#{age} where id=#{id}

    </update>

    <select id="getAllUsers" resultType="com.mybatis.test.User">

        select * from users

    </select>

</mapper>

CRUD代码:

SqlSession session=factory.openSession(true);//true表示自动提交

              //String statement="com.mybatis.test.userMapper.addUser";

              //int num=session.insert(statement, new User(-1,"fei5", 21));

              //String statement="com.mybatis.test.userMapper.updateUser";

              //int user= session.update(statement,new User(3,"feip", 21));

              //String statement="com.mybatis.test.userMapper.deleteUser";

              //int num=session.delete(statement, 4);

4.优化:

4.1 配置文件的优化:

新建db.properties文件:

driver=com.mysql.jdbc.Driver

url=jdbc:mysql://localhost:3306/mysql

username=root

password=x5uq4xWjTvUMH23H

然后在conf.xml文件中使用<propertyes  resource= "db. properties"> 设置引用,并使用${key}的形式将对应的值引用进来。从而方便数据库的管理。

<dataSource type="POOLED">

                            <property name="driver" value="${driver}"/>

                            <property name="url" value="${url}"/>

                            <property name="username" value="${username}"/>

                            <property name="password" value="${password}"/>

</dataSource>

4.2 引用实体类引用的优化:

<typeAliases>

        <typeAlias type="com.mybatis.test.User" alias="_User"/>

        <package name="com.mybatis.test"/>

    </typeAliases>
<select id="getUser" parameterType="int" resultType="User">

        select * from users where id=#{id}

 </select>

可以使用以上的typeAlias别名或者package路径,typeAlias在mapper文件中可以直接使用alias="_User"中的_User,使用package可以直接使用User类名,进行简化。如:

4.3 字段名与实体属性名不相同时的冲突:

实体类中:

数据库中:

查询结果为:null

解决方法:

(1). 使用数据库别名语法:别名必须要与实体类中的属性名相同

Select id user_id,name user_name, age user_age from users where id=#{id}

(2). 别名配置:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">

<mapper namespace="com.mybatis.test2.userMapper">

   <select id="getUser" parameterType="int" resultMap="getUserT">

       select * from users where id=#{user_id}

   </select>

   <resultMap type="User" id="getUserT">

       <!--

                     id表示数据库表中的主键字段;

                     property表示实体类中的属性名;

                     column 表示数据表中对应的字段名。

        -->

       <id property="user_id" column="id"/>

       <result property="user_name" column="name"/>

       <result property="user_age" column="age"/>

   </resultMap>

</mapper>

5.一对一联表查询:

ALTER TABLE product ADD CONSTRAINT fk _id FOREIGN KEY(u_id) REFERENCES users(id)

方法一:     嵌套结果查询,使用嵌套结果映射来处理重复的联合结果的子集封装关联表查询的数据(去重复的数据)

Product.java:

User.java:

ProductMapper.xml:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">

<mapper namespace="com.mybatis.test3.ProductMapper">

   <select id="getProduct" parameterType="int" resultMap="getProductMap">

       SELECT * FROM users u, product p WHERE p.u_id=u.id AND p.p_id=#{id}

   </select>

   <resultMap type="Product" id="getProductMap">

       <id property="id" column="p_id"/>

       <result property="name" column="p_name"/>

       <result property="u_id" column="u_id"/>

       <association property="user" javaType="User">

           <id property="user_id" column="id"/>

           <result property="user_name" column="name"/>

           <result property="user_age" column="age"/>

       </association>

   </resultMap>

</mapper>
Product product=session.selectOne(statement,5);String statement = "com.mybatis.test3.ProductMapper.getProduct";

System.out.println(product);

session.close();

测试结果:

Product [name=Chanel, id=5, u_id=5, user=User [user_id=5, user_name=feit, user_age=21]]

方法二 :嵌套查询,通过执行另一个SQL映射语句来返回预期的复杂类型。

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">

<mapper namespace="com.mybatis.test3.ProductMapper">

   <select id="getProduct2" resultMap="getProductMap2">

       SELECT * FROM product WHERE p_id=#{id}

   </select>

   <select id="getUser" parameterType="int" resultType="User">

       SELECT id user_id,name user_name,age user_age FROM users WHERE id=#{user_id}

   </select>

   <resultMap type="Product" id="getProductMap2">

       <id property="id" column="p_id"/>

       <result property="name" column="p_name"/>

       <result property="u_id" column="u_id"/>

       <!-- 通过select属性指向第二次select 的id,执行第二次查询,并通过column字段[外键]将第一次结果集中的user数据查询出来-->

       <association property="user" column="u_id" select="getUser">

       </association>

   </resultMap>

</mapper>

MyBatis框架的更多相关文章

  1. Mybatis框架的多对一关联关系(六)

    一.一对多的关联映射 一对多关联查询多表数据 1接口 public interface IDeptDAO { //根据部门编号查询该部门单个查询 public Emp getEmpById(Integ ...

  2. Spring+SpringMvc+Mybatis框架集成搭建教程

    一.背景 最近有很多同学由于没有过SSM(Spring+SpringMvc+Mybatis , 以下简称SSM)框架的搭建的经历,所以在自己搭建SSM框架集成的时候,出现了这样或者那样的问题,很是苦恼 ...

  3. Mybatis框架中实现双向一对多关系映射

    学习过Hibernate框架的伙伴们很容易就能简单的配置各种映射关系(Hibernate框架的映射关系在我的blogs中也有详细的讲解),但是在Mybatis框架中我们又如何去实现 一对多的关系映射呢 ...

  4. Hibernate框架与Mybatis框架的对比

    学习了Hibernate和Mybatis,但是一直不太清楚他们两者的区别的联系,今天在网上翻了翻,就做了一下总结,希望对大家有帮助! 原文:http://blog.csdn.net/firejuly/ ...

  5. 初识Mybatis框架,实现增删改查等操作(动态拼接和动态修改)

    此第一次接触Mybatis框架确实是有点不适应,特别是刚从Hibernate框架转转型过来,那么为什么要使用Mybatis框架,Mybatis框架和Hibernate框架又有什么异同呢? 这个问题在我 ...

  6. Spring+MyBatis框架中sql语句的书写,数据集的传递以及多表关联查询

    在很多Java EE项目中,Spring+MyBatis框架经常被用到,项目搭建在这里不再赘述,现在要将的是如何在项目中书写,增删改查的语句,如何操作数据库,以及后台如何获取数据,如何进行关联查询,以 ...

  7. SSM框架-----------SpringMVC+Spring+Mybatis框架整合详细教程

    1.基本概念 1.1.Spring Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One  ...

  8. Spring3.0 与 MyBatis框架 整合小实例

    本文将在Eclipse开发环境下,采用Spring MVC + Spring + MyBatis + Maven + Log4J 框架搭建一个Java web 项目. 1. 环境准备: 1.1 创建数 ...

  9. 手把手Maven搭建SpringMVC+Spring+MyBatis框架(超级详细版)

    手把手Maven搭建SpringMVC+Spring+MyBatis框架(超级详细版) SSM(Spring+SpringMVC+Mybatis),目前较为主流的企业级架构方案.标准的MVC设计模式, ...

  10. 详解Java的MyBatis框架中SQL语句映射部分的编写

    这篇文章主要介绍了Java的MyBatis框架中SQL语句映射部分的编写,文中分为resultMap和增删查改实现两个部分来讲解,需要的朋友可以参考下 1.resultMap SQL 映射XML 文件 ...

随机推荐

  1. IntelliJ IDEA通过Spring配置连接MySQL数据库

    先从菜单View→Tool Windows→Database打开数据库工具窗口,如下图所示: 点击Database工具窗口左上角添加按钮"+",选择Import from sour ...

  2. foxmail 6.5升级到7.0版本后,旧邮件的导入处理

    随着foxmail 7.0版的火热升级,部分从foxmial 6.5版升级到7.0版的用户可能会出现旧邮件丢失的困扰.这里,foxmail为大家提供的解决方案如下:   打开Foxmail,点击 文件 ...

  3. Python处理Excel文档(xlrd, xlwt, xlutils)

    简介 xlrd,xlwt和xlutils是用Python处理Excel文档(*.xls)的高效率工具.其中,xlrd只能读取xls,xlwt只能新建xls(不可以修改),xlutils能将xlrd.B ...

  4. shell下root用户切换其他用户运行程序

    工作中,一些程序,需要随机启动,但是不是以root用户运行,于是需要在rc.local中通过shell,从root用户切换到其他用户运行程序,命令如下: su -c 'command' - user ...

  5. MVC entity

    1>MVC entity 1)Employee public string Id{get;private set;} public string Name{get;private set;} p ...

  6. HDU 1532 (Dinic算法)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1532 题目大意: 就是由于下大雨的时候约翰的农场就会被雨水给淹没,无奈下约翰不得不修建水沟,而且是网络 ...

  7. FileSystemWatcher

    转:http://www.cnblogs.com/zhaojingjing/archive/2011/01/21/1941586.html 注意:用FileWatcher的Created监控文件时,是 ...

  8. Expert C# 5.0中的Linq部分

    1.先看看.NET中的Linq 2.扩展方法 3.Lambda表达式和表达式树 4.Linq中的延迟操作 5.Linq中的查询方法 5.1分割操作 5.2连接操作 5.3排序操作 5.4分组和连接 5 ...

  9. M2M

    1, M2M (数据算法模型) M2M是将数据从一台终端传送到另一台终端,也就是机器与机器(Machine to Machine)的对话.   M2M简介 但从广义上M2M可代表机器对机器(Machi ...

  10. Java线程新特性--- Lock

    在Java5中,专门提供了锁对象,利用锁可以方便的实现资源的封锁,用来控制对竞争资源并发访问的控制,这些内容主要集中在java.util.concurrent.locks包下面,里面有三个重要的接口C ...