What is MyBatis?
Comparison with Hibernate
- Mybatis:It is lightweight, simple, and has excellent performance. It can be optimized for SQL and has low learning costs.
- Hibernate: Good database independence, strong O/R ing ability, high development efficiency, high learning costs, and difficult to master.
- Summary:Both are excellent persistent layer frameworks, which can greatly improve development efficiency after being proficient. However, individuals prefer mybatis, Which is lightweight, flexible, and has excellent performance.
Official Mybatis Architecture
For more information, see the official documentation (Chinese)
Http://mybatis.github.io/mybatis-3/zh/getting-started.html
The following is a simple example of second-level cache implementation based on ehcache using spring + mybatis annotation.
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
There is no need to register all the mappers in the XML configuration file of Spring. Instead, you can use a MapperScannerConfigurer to search for the er under the class path and automatically create MapperFactoryBean.
The basePackage attribute allows you to set the basic package path for the Mapper interface file. You can use semicolons or commas as separators to set more than one package path. Each mapper is recursively searched in the specified package path.
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 configurationlog4j.rootLogger=info, stdout# MyBatis logging configuration...log4j.logger.org.mybatis.example.BlogMapper=DEBUG# Console output...log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%nlog4j.logger.java.sql=info,stdout
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; }}
There should be some annotations for establishing mappings with database tables.
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);}
Previously, mybatis was used to configure mapper in xml. Now annotations are found, so it is very convenient to use annotations.
However, it seems that the official site prefers the xml method, saying that the core functions of mybatis are embodied in xml. With in-depth understanding, no helper classes can be inherited by Mapper are found, so the basic curd must be written by yourself.
Some netizens wrote the dependency org. apache. ibatis. jdbc. sqlBuilder has written a general template, but SqlBuilder is no longer recommended. Therefore, we recommend that you use back-to-xml configuration for the mybatis official project to maximize its effectiveness.
Junit testing class
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()); }}
The log shows that the findUserByName method reads the cache.