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 对于语言的学习而言,马上上手去编程,多多练习 ...
 
随机推荐
- MyBatis 延迟加载,一级缓存,二级缓存设置
			
什么是延迟加载 resultMap中的association和collection标签具有延迟加载的功能. 延迟加载的意思是说,在关联查询时,利用延迟加载,先加载主信息.使用关联信息时再去加载关联信息 ...
 - Javascript自执行匿名函数(function() { })()的原理分析
			
匿名函数指没有指定函数名或指针的函数,自执行匿名函数只是其中一种,下文中称这种函数为:自执行函数 下面是一个最常见的自执行函数: // 传统匿名函数 (function() { alert('hell ...
 - LAMP(1) 在VirtualBox里安装Ubuntu Server
			
问题0.虚拟机中安装lamp环境 问题解决: 来自百度经验 问题1. 用putty远程登陆linux系统,显示network error connection refused 问题解决 问题2. my ...
 - Android 样式 (style) 和主题(theme)
			
转载:https://gold.xitu.io/post/58441c48c59e0d0056a30bc2 样式和主题 样式是指为 View 或窗口指定外观和格式的属性集合.样式可以指定高度.填充.字 ...
 - webfrom 总结
			
网上看了很多理论,然而知易行难.在实际工作中还是存在很多问题. 下面是使用webform过程中的总结. 1.不使用服务端控件 表单有post和get两种方法,可以通过 form methed='pos ...
 - Jquery获取offsetHeight
			
纯javascript: window.document.getElementById('MainColumn').offsetHeight jquery: $('#id').get(0).offse ...
 - DOM解析XML报错:Content is not allowed in prolog
			
报错内容为: Content is not allowed in prolog. Nested exception: Content is not allowed in prolog. 网上所述总结来 ...
 - python之生成器
			
def repeater(value): while True: new = yield value print(first, new) if new is not None: value = new ...
 - Selenium+python 配置
			
1. 安装python, www.python.org. 下载最新的python,应该是32位的.注意配置环境变量. 2. 安装PIP(pip是一个以Python计算机程序语言写成的软件包管理系统). ...
 - U盘存放大于4G数据文件且无须格式化U盘的解决方法
			
现在优盘的容量越来越大了,价格越来越便宜,可是它也有个缺点,因为它默认的文件系统是"FAT32",这种文件系统最大只能保存4G的文件,超过4G的文件就不能保存在优盘上了,这样就不能 ...