什么是 MyBatis?

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

与Hibernate比较

  • mybatis:更加轻巧,简单,性能优,可以针对sql优化,学习成本低。
  • Hibernate:数据库无关性好,O/R映射能力强,开发效率高,学习成本高,且难精通。
  • 总结:两者都是非常优秀的持久层框架,精通后能大大提高开发效率。不过,个人更倾向于mybatis,轻巧,灵活,且性能优。

Mybatis官方架构图

相关入门知识见官方文档(有中文)

http://mybatis.github.io/mybatis-3/zh/getting-started.html

下面是一个spring+mybatis用注解的方式基于ehcache实现二级缓存的简单例子

mybatis-configuration.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:ehcache="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring
http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring/ehcache-spring-1.1.xsd">
<context:component-scan base-package="com.dempe.summer.app.user" /> <!-- Enables the Spring MVC @Controller programming model -->
<mvc:annotation-driven />
<ehcache:annotation-driven cache-manager="ehCacheManager" /> <bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://172.30.254.38:5000/test" />
<property name="username" value="azheng" />
<property name="password" value="123" />
</bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.dempe.summer.app.user.persist" />
</bean> <bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache-mybatis.xml" />
</bean> </beans>

MapperScannerConfigurer

没有必要在 Spring 的 XML 配置文件中注册所有的映射器。相反,你可以使用一个 MapperScannerConfigurer , 它 将 会 查 找 类 路 径 下 的 映 射 器 并 自 动 将 它 们 创 建 成 MapperFactoryBean。

basePackage 属性是让你为映射器接口文件设置基本的包路径。 你可以使用分号或逗号 作为分隔符设置多于一个的包路径。每个映射器将会在指定的包路径中递归地被搜索到。

ehcache-mybatis.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" updateCheck="false">
<!--
| Please see http://ehcache.sourceforge.net/documentation/configuration.html for
| detailed information on how to configurigure caches in this file
+-->
<!-- Location of persistent caches on disk -->
<diskStore path="java.io.tmpdir/EhCacheSpringAnnotationsExampleApp" /> <defaultCache eternal="false" maxElementsInMemory="1000"
overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0"
timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU"/> <cache name="testCache" eternal="false"
maxElementsInMemory="100" overflowToDisk="false" diskPersistent="false"
timeToIdleSeconds="0" timeToLiveSeconds="300"
memoryStoreEvictionPolicy="LRU" /> </ehcache>

  log4j.properties

# Global logging configuration
log4j.rootLogger=info, stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n log4j.logger.java.sql=info,stdout

  

 log4j.logger.java.sql=info,stdout,打开sql语句开关,级别为info,可以输出sql语句,方便查看缓存是否生效

UserModel

package com.dempe.summer.app.user.model;

import java.io.Serializable;

/**
* @author: Zheng Dongping
* @version 1.0 date: 2013-12-23
*/
public class UserModel implements Serializable { private static final long serialVersionUID = 1L; private Integer id; private String username; private String password; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} }

这里应该会有一些和数据库表建立映射关系的注解。  

UserMapper

package com.dempe.summer.app.user.persist;

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select; import com.dempe.summer.app.user.model.UserModel;
import com.googlecode.ehcache.annotations.Cacheable; /**
* @author: Zheng Dongping
* @version 1.0 date: 2013-12-23
*/
public interface UserMapper { @Select("SELECT * FROM user_info WHERE username = #{username} and password = #{password}")
UserModel findUserByNameAndPassword(UserModel user); @Cacheable(cacheName = "testCache")
@Select("SELECT * FROM user_info WHERE username = #{username}")
UserModel findUserByName(@Param("userName") String userName); }

之前用mybatis一直是xml配置mapper的方式,现在发现了注解,所以尝试了用注解,感觉很方便。

但貌似官方比较推崇xml方式,说mybatis的核心功能都在xml中体现。随着深入了解,没有找到Mapper可以继承的辅助类,所以基础的curd都得自己写。

有网友写了依赖org.apache.ibatis.jdbc.SqlBuilder写了通用的模板,但是现在SqlBuilder已经不被推荐使用,所以建议mybatis正式项目还是用回xml配置的方式,发挥最大的功效。

junit测试类

package com.dempe.summer.mybatis;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.dempe.summer.app.user.model.UserModel;
import com.dempe.summer.app.user.persist.UserMapper; /**
* @author: Zheng Dongping
* @version 1.0 date: 2013-12-23
*/
@ContextConfiguration("/mybatis-configuration.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class MybatisTest { @Resource
private UserMapper userMapper; @Test
public void test() {
UserModel user = new UserModel();
user.setPassword("123");
user.setUsername("dempe");
UserModel um2 = userMapper.findUserByName("dempe");
for (int i = 0; i < 100; i++) {
userMapper.findUserByName("dempe");
} System.out.println("-----------------------------------------------");
for (int i = 0; i < 10; i++) {
userMapper.findUserByNameAndPassword(user);
} System.out.println(um2.getUsername());
} }

 通过日志可以看到,findUserByName方法是有读到缓存的。

java 持久框架mybatis的初步学习的更多相关文章

  1. Java数据持久层框架 MyBatis之API学习一(简介)

    对于MyBatis的学习而言,最好去MyBatis的官方文档:http://www.mybatis.org/mybatis-3/zh/index.html 对于语言的学习而言,马上上手去编程,多多练习 ...

  2. Java数据持久层框架 MyBatis之API学习八(Java API详解)

    对于MyBatis的学习而言,最好去MyBatis的官方文档:http://www.mybatis.org/mybatis-3/zh/index.html 对于语言的学习而言,马上上手去编程,多多练习 ...

  3. Java数据持久层框架 MyBatis之API学习九(SQL语句构建器详解)

    对于MyBatis的学习而言,最好去MyBatis的官方文档:http://www.mybatis.org/mybatis-3/zh/index.html 对于语言的学习而言,马上上手去编程,多多练习 ...

  4. Java数据持久层框架 MyBatis之API学习七(动态 SQL详解)

    对于MyBatis的学习而言,最好去MyBatis的官方文档:http://www.mybatis.org/mybatis-3/zh/index.html 对于语言的学习而言,马上上手去编程,多多练习 ...

  5. Java数据持久层框架 MyBatis之API学习六(Mapper XML 文件详解)

    对于MyBatis的学习而言,最好去MyBatis的官方文档:http://www.mybatis.org/mybatis-3/zh/index.html 对于语言的学习而言,马上上手去编程,多多练习 ...

  6. Java数据持久层框架 MyBatis之API学习四(xml配置文件详解)

    摘录网址: http://blog.csdn.net/u010107350/article/details/51292500 对于MyBatis的学习而言,最好去MyBatis的官方文档:http:/ ...

  7. Java数据持久层框架 MyBatis之API学习二(入门)

    对于MyBatis的学习而言,最好去MyBatis的官方文档:http://www.mybatis.org/mybatis-3/zh/index.html 对于语言的学习而言,马上上手去编程,多多练习 ...

  8. Java数据持久层框架 MyBatis之API学习十(Logging详解)

    对于MyBatis的学习而言,最好去MyBatis的官方文档:http://www.mybatis.org/mybatis-3/zh/index.html 对于语言的学习而言,马上上手去编程,多多练习 ...

  9. Java数据持久层框架 MyBatis之API学习五(Mapper XML 文件)

    对于MyBatis的学习而言,最好去MyBatis的官方文档:http://www.mybatis.org/mybatis-3/zh/index.html 对于语言的学习而言,马上上手去编程,多多练习 ...

随机推荐

  1. Canvas电子签名和游戏化

    今天一天的时间都在做包团报价的无流程原型设计,一方面参考了其他系统,一方面整理先在系统中不合理的部分,规范了报价元素的分类.梳理了意向需求,其实原来粗略的放了一个模板进去是听不靠谱的.客户的要求-&g ...

  2. perl

    introduction: http://www.yiibai.com/perl/perl_introduction.html functions: http://www.yiibai.com/per ...

  3. jquery和zepto的扩展方法extend

    jquery和zepto的扩展方法extend 总结下jQuery(3.1.1)和zepto(1.1.6)到底是如何来开放接口,使之可以进行扩展,两者都会有类型判断,本文使用简单的类型判断,暂不考虑兼 ...

  4. Java常见Exception整理

    前言: 技术开发入坑近1年,摸打滚爬,各种升级打怪.因目前从事Java相关,故整理了一下并把常见的异常(Exception)贴出来,一来为了后续提醒自己,二来供即将入坑的朋友打一下预防针!A级(代码逻 ...

  5. 使用XHR2或Jsonp实现跨域以及实现原理

    我们直接使用XMLHttpRequset请求外部接口 会发现 报这个错误 其实浏览器成功发送请求并拿回了数据  只是浏览器的同源策略 禁止了获取  在xhr2 服务器端支持跨域 需要在响应头增加 Ac ...

  6. jQuery 运行机制

    1.Selector,查找元素.这个查找不但包含基于CSS1~CSS3的CSS Selector功能,还包含其对直接查找或间接查找而扩展的一些功能. 2.Dom元素的属性操作.Dom元素可以看作htm ...

  7. Codeforces 710F String Set Quries

    题意 维护一个字符串的集合\(D\), 支持3种操作: 插入一个字符串\(s\) 删除一个字符串\(s\) 查询一个字符串\(s\)在\(D\)中作为子串出现的次数 强制在线 解法 AC自动机+二进制 ...

  8. coreseek安装过程

    一.sphinx 全文检索 通过sphinx检索到id,然后到mysql里面拿到记录 什么是劝我呢检索?结构化数据: 具有固定格式或者长度的数据非结构化数据: 标题 内容 等不定长的数据非机构化数据还 ...

  9. 【原创】贴个dirtycow(脏牛漏洞)不死机的exploit

    dirtycow官网上几个获得rootshell的exp大都会导致机器死机,在原作者的基础上改进了一下,做个记录: /* * (un)comment correct payload first (x8 ...

  10. 机器学习——Logistic回归

    1.基于Logistic回归和Sigmoid函数的分类 2.基于最优化方法的最佳回归系数确定 2.1 梯度上升法 参考:机器学习--梯度下降算法 2.2 训练算法:使用梯度上升找到最佳参数 Logis ...