java 持久框架mybatis的初步学习
什么是 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的初步学习的更多相关文章
- Java数据持久层框架 MyBatis之API学习一(简介)
对于MyBatis的学习而言,最好去MyBatis的官方文档:http://www.mybatis.org/mybatis-3/zh/index.html 对于语言的学习而言,马上上手去编程,多多练习 ...
- Java数据持久层框架 MyBatis之API学习八(Java API详解)
对于MyBatis的学习而言,最好去MyBatis的官方文档:http://www.mybatis.org/mybatis-3/zh/index.html 对于语言的学习而言,马上上手去编程,多多练习 ...
- Java数据持久层框架 MyBatis之API学习九(SQL语句构建器详解)
对于MyBatis的学习而言,最好去MyBatis的官方文档:http://www.mybatis.org/mybatis-3/zh/index.html 对于语言的学习而言,马上上手去编程,多多练习 ...
- Java数据持久层框架 MyBatis之API学习七(动态 SQL详解)
对于MyBatis的学习而言,最好去MyBatis的官方文档:http://www.mybatis.org/mybatis-3/zh/index.html 对于语言的学习而言,马上上手去编程,多多练习 ...
- Java数据持久层框架 MyBatis之API学习六(Mapper XML 文件详解)
对于MyBatis的学习而言,最好去MyBatis的官方文档:http://www.mybatis.org/mybatis-3/zh/index.html 对于语言的学习而言,马上上手去编程,多多练习 ...
- Java数据持久层框架 MyBatis之API学习四(xml配置文件详解)
摘录网址: http://blog.csdn.net/u010107350/article/details/51292500 对于MyBatis的学习而言,最好去MyBatis的官方文档:http:/ ...
- Java数据持久层框架 MyBatis之API学习二(入门)
对于MyBatis的学习而言,最好去MyBatis的官方文档:http://www.mybatis.org/mybatis-3/zh/index.html 对于语言的学习而言,马上上手去编程,多多练习 ...
- Java数据持久层框架 MyBatis之API学习十(Logging详解)
对于MyBatis的学习而言,最好去MyBatis的官方文档:http://www.mybatis.org/mybatis-3/zh/index.html 对于语言的学习而言,马上上手去编程,多多练习 ...
- Java数据持久层框架 MyBatis之API学习五(Mapper XML 文件)
对于MyBatis的学习而言,最好去MyBatis的官方文档:http://www.mybatis.org/mybatis-3/zh/index.html 对于语言的学习而言,马上上手去编程,多多练习 ...
随机推荐
- 手机端html5触屏事件(touch事件)
touchstart:触摸开始的时候触发 touchmove:手指在屏幕上滑动的时候触发 touchend:触摸结束的时候触发 而每个触摸事件都包括了三个触摸列表,每个列表里包含了对应的一系列触摸点( ...
- OBS MAC 系统开发(基于mac OS X 10.12)
按照github 上的说明,安装配套软件,和跟踪需要的库 推荐使用homebrew 来安装各种依赖库. 安装Qt后,要配置系统变量 ,这个困扰本人很久:) 成功编译 cmake .. &&am ...
- iOS中获取当前时间,设定时间,并算出差值
NSDate *date = [NSDate date];//获取当前时间 NSTimeZone *zone = [NSTimeZone systemTimeZone];//修改时区 NSIntege ...
- c++中的lambda特性
来源: http://www.jb51.net/article/56147.htm cocos2dx3.0测试: 1.有参数a,b printf("lambda=%lf", []( ...
- 用Redis实现分布式锁
Redis有一系列的命令,特点是以NX结尾,NX是Not eXists的缩写,如SETNX命令就应该理解为:SET if Not eXists.这系列的命令非常有用,这里讲使用SETNX来实现分布式锁 ...
- Hadoop MapReduce执行过程详解(带hadoop例子)
https://my.oschina.net/itblog/blog/275294 摘要: 本文通过一个例子,详细介绍Hadoop 的 MapReduce过程. 分析MapReduce执行过程 Map ...
- js拖拽原理和碰撞原理
拖拽的原理onmousedown 选择元素onmousemove 移动元素onmouseup 释放元素 1:如果拖拽的时候有文字:被选中,会产生问题原因:当鼠标按下的时如果页面中有文字或者图片被选中的 ...
- Java学习笔记之方法重载
被重载的方法必须具有不同的参数列表.不能基于不同修饰符或返回值类型来重载方法. package welcome; public class TestMethodOverloading { public ...
- C#通过WebClient/HttpWebRequest实现http的post/get方法
C#通过WebClient/HttpWebRequest实现http的post/get方法 http://www.cnblogs.com/shadowtale/p/3372735.html
- java内存泄漏的几种情况
转载于http://blog.csdn.net/wtt945482445/article/details/52483944 Java 内存分配策略 Java 程序运行时的内存分配策略有三种,分别是静态 ...