JavaORM框架之Mybatis篇(Ibatis)

欢迎查看Java开发之上帝之眼系列教程,如果您正在为Java后端庞大的体系所困扰,如果您正在为各种繁出不穷的技术和各种框架所迷茫,那么本系列文章将带您窥探Java庞大的体系。本系列教程希望您能站在上帝的角度去观察(了解)Java体系。使Java的各种后端技术在你心中模块化;让你在工作中能将Java各个技术了然于心;能够即插即用。本章我们来一起了解ORM(对象关系映射关系)框架之Mybatis(Ibatis)。

 

主流ORM框架有Mybatis和Hibernate,本章我们将对Mybatis的核心要点进行了解。
 

什么是ORM(对象映射关系)框架?

 ORM(Object Relational Mapping)对象关系映射,是 一种为了解决面向对象与关系型数据库不匹配而出现的技术,使开发者能够用面向对象的方式使用关系型数据库。

Mybatis和Hibernate有什么异同?

  1. Mybatis简单,Hibernate较复杂,门槛高。
  2. Mybatis自定制Sql,比Hibernate灵活,可控
  3. Mybatis与数据库映射得到的PO与Hibernate映射PO意义不同

Mybatis入门起步   Mybatis入门起步完整示例下载

/**
 * @Author:jimisun
 * @Description:
 * @Date:Created in 08:37 2018-09-24
 * @Modified By:
 */
public class Main {
    
    public static void main(String[] args) throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        TestUserMapper mapper = sqlSession.getMapper(TestUserMapper.class);
        TestUser testUser = mapper.selectOne(1);
        System.out.println(testUser.toString());
    }
}
PS:Mybatis支持注解开发,但需要保留空的XML文件,也就是保留空的命名空间 ; 如下所示
    @Select(" SELECT * from user where id = #{id};")
    MyDto selectOne(Integer id);
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.jimisun.dao.TestUserMapper">
   <!---->
</mapper>

 

Mybatis和Spring的集成 Myabtis和Spring整合完整示例代码下载

如果你使用Mybatis那么一定会使用Spring,最常见的框架组合就是SSM(SpringMvc+Spring+Mybatis),那么Mybatis针对和Spring的整合提供了一个类库(jar包)
     <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.2</version>
        </dependency>
以前我们配置在mybatis里面的配置,现在我们可以将这些配置转移到了Spring配置中;统一交给Spring进行管理, Mybatis的配置文件留空,但是不能删除哟
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!-- 加载配置文件 -->
    <context:property-placeholder location="classpath:db.properties"/>

    <!-- 数据库连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="maxActive" value="10"/>
    </bean>

    <!-- mapper配置 -->
    <!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 数据库连接池 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 加载mybatis的全局配置文件 -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!-- 扫描entity包 使用别名 -->
        <property name="typeAliasesPackage" value="com.jimisun.domain"/>
        <!-- 扫描sql配置文件:mapper需要的xml文件 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml" />
    </bean>

    <!-- 配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- 给出需要扫描Dao接口包 -->
        <property name="basePackage" value="com.jimisun.dao"/>
    </bean>

</beans>

Spring和Myabtis整合的有两个关注点

  1. Myabtis将SqlSessionFactory交付Spring管理
  2. Spring将XML对应的接口进行接手管理

 

Mybatis结果映射 Myabtis自定义结果映射完整示例代码下载

在实际项目中我们通过使用mybatis查询数据库经常使用多表查询,关联查询,或者实体的属性名和数据库列名不符等情况...所以查询的结果存在不定性,我们可以自定义Dto类,在mapper.xml文件中自定义<resultMap>标签即可。
    <resultMap id="MyDto" type="com.jimisun.domain.dto.MyDto">
        <result property="myid" column="id"></result>
        <result property="myusername" column="username"></result>
    </resultMap>

 

Mybatis二级缓存 Mybatis的二级缓存测试示例代码

虽然很多时候我们在开发中并不经常Mybatis的二级缓存 , 但是如果针对个别SQL进行优化设置能够极大提升访问数据库效率 . mybatis支持一级缓存和二级缓存,默认开启一级缓存,一级缓存使SqlSession级别的,Session结束缓存就清空了,二级缓存使Mapper级别的,需要我们手动开启。
     <!--开启二级缓存-->
     <cache/>
针对不需要使用二级缓存的方法设置useCache=false
   <select id="selectOne" parameterType="java.lang.Integer" resultType="com.jimisun.domain.TestUser" useCache="false">
      SELECT * from user where id = #{id}
   </select>

我们进行简单的测试 , 观察Mybatis二级缓存是否开启

    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
        TestUserMapper testUserMapper = (TestUserMapper) context.getBean("testUserMapper");
        /*测试缓存:先查询此时username为jimisun*/
        TestUser testUser = testUserMapper.selectOne(1);
        /*测试缓存:修改username为lisi*/
        Integer integer = testUserMapper.updateOne(1);
        /*测试缓存:最后查询查看是否从数据库获取还是从缓存获取*/
        TestUser resultUser = testUserMapper.selectOne(1);
        System.out.println(resultUser.toString());
    }

 

Mybatis其他使用技巧

  • 在mapper.xml编写sql时对于重复的sql我们可以使用<include refid="id">引用代码
  • 对于Mybatis非空判断我们建议这样使用 <if test="param !=null and param != ''">
  • 一个Mapper.xml中可以直接引用另一个Mapper.xml的resultMap , 不需要重复定义

 


 

勘误&感谢

  本系列文章资料来源很多出自于互联网和在下本身的见解,受限于个人技术能力水平和其他相关知识的限制,相关见解错误或者资料引用错误请各位帮助留言校正!引用资料多来自于互联网,在下在引用前会遵循各位前辈或者博主的引用说明表示感谢,但互联网资料多是转发再转发或存在遗漏请原作者内信联系指正。

 

posted @ 2018-09-28 10:39  jimisun  阅读(6116)  评论(0编辑  收藏  举报
豫ICP备17005230号-3