什么是 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. 篇三:MySQL分页

    分页:物理分页.逻辑分页 物理分页:SQL语句中直接使用limit 逻辑分页:先查询出所有满足条件的数据,然后在Java中截取需要的行 优缺点: 1.逻辑分页翻页速度快,第一次查询出来的数据会有缓存, ...

  2. 命令行工具aspnet_regiis.exe实现加密和解密web.config

    命令行工具aspnet_regiis.exe,是一个类似于DOS的命令工具,称之为命令解释器.使用命令行工具加密和解密web.config文件中的数据库连接字符串时,只需要简单的语法命令即可. 加密语 ...

  3. volatile修饰符

    Volatile 修饰的成员变量在每次被线程访问时,都强制从共享内存中重新读取该成员变量的值.而且,当成员变量发生变化时,会强制线程将变化值回写到共享内存.这样在任何时刻,两个不同的线程总是看到某个成 ...

  4. HTML隐藏的方法

    display:none; 表单 type="hidden" 宽高设为0 height:0;width:0; 祖先元素隐藏或在页面外 margin Visibility:hidde ...

  5. JavaScript工具代码

    html编码 function htmlEscape(sHtml){ return sHtml && sHtml.replace(/[<>&"]/g, f ...

  6. Apache的dbutils的架构图

  7. 计算机视觉之《OpenCV开发环境搭建》

    codeblock安装:http://blog.csdn.net/hitwengqi/article/details/7985343 ubuntu+codeblock+opencv:http://bl ...

  8. ThinkPhp 3.2 ajax无刷新分页(未完全改完,临时凑合着用)

    临时更改后的page类(很多地方没修改...因为笔者PHP没学好..)如下: <?phpnamespace Fenye\libs; /**  file: page.class.php   完美分 ...

  9. checkbox的全选与反选

    最近在做一个项目,其中一个功能就是多选框的全选与反选.感觉很简单的小功能,一下子想不起来怎么实现了,很是耽误时间.我在想,我有必要整理下自己的一些小demo了,也方便以后再使用的时候能快速的完成功能. ...

  10. 美团HD(4)-二级联动效果

    DJNavDropView.m #import "DJNavDropView.h" #import "DJCategory.h" #import "D ...