java 持久框架mybatis的初步學習

什麼是 MyBatis?

MyBatis 是支持普通 SQL 查詢,存儲過程和高級映射的優秀持久層框架。MyBatis 消除 了幾乎全部的 JDBC 代碼和參數的手工設置以及結果集的檢索。MyBatis 使用簡單的 XML 或註解用於配置和原始映射,將接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java 對象)映射成數據庫中的記錄。html

與Hibernate比較java

  • mybatis:更加輕巧,簡單,性能優,能夠針對sql優化,學習成本低。
  • Hibernate數據庫無關性好,O/R映射能力強,開發效率高,學習成本高,且難精通。
  • 總結:二者都是很是優秀的持久層框架,精通後能大大提升開發效率。不過,我的更傾向於mybatis,輕巧,靈活,且性能優。

Mybatis官方架構圖mysql

 

相關入門知識見官方文檔(有中文)git

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

 

下面是一個spring+mybatis用註解的方式基於ehcache實現二級緩存的簡單例子spring

 mybatis-configuration.xmlsql

<?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 屬性是讓你爲映射器接口文件設置基本的包路徑。 你可使用分號或逗號 做爲分隔符設置多於一個的包路徑。每一個映射器將會在指定的包路徑中遞歸地被搜索到。apache


ehcache-mybatis.xml
spring-mvc

 

<?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方法是有讀到緩存的。

相關文章
相關標籤/搜索