码迷,mamicode.com
首页 > 编程语言 > 详细

Spring集成MyBatis框架

时间:2017-10-04 21:35:17      阅读:347      评论:0      收藏:0      [点我收藏+]

标签:hold   close   port   lazyload   xsd   gen   dom   jdbc   resources   

(一).MyBatis介绍

MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。

创建MyBatis SQL映射XML文件:MyBatis Generator配置示例

MyBatis配置,创建resources/mybatis/mybatis.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org/DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <settings>
        <setting name="lazyLoadingEnabled" value="false"/>
        <!-- 设置mybatis内置日志工厂 -->
        <setting name="logImpl" value="LOG4J"/>
        <!-- 支持Null值(value)输出Key -->
        <setting name="callSettersOnNulls" value="true"/>
    </settings>
</configuration>

Maven导入MyBatis相关依赖,编辑pom.xml

        <!-- 导入database依赖,使用druid作连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.3</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.44</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.10.RELEASE</version>
        </dependency>

 

(二).方法一(通过MapperScannerConfigurer实现,直接对Mapper接口进行代理)

数据库相关bean对象配置,创建resources/spring/applicationContext_database.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- 引入配置文件 -->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:/mybatis/db.properties"/>
    </bean>

    <!-- dataSource配置 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          init-method="init" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>

        <property name="filters" value="log4j"/>
        <property name="maxActive" value="5"/>
        <property name="initialSize" value="1"/>
        <property name="maxWait" value="6000"/>
    </bean>

    <!-- mybatis文件配置,mapper.xml文件扫描 -->
    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:/mybatis/mybatis.xml"/>
        <property name="mapperLocations" value="classpath:/mybatis/*Mapper.xml"/>
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- mapper注解扫描器配置,扫描@MapperScan注解,自动生成代码对象 -->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.learn.spring.server.dao"/>
        <property name="sqlSessionFactoryBeanName" value="sessionFactory"/>
    </bean>
</beans>

UserDOMapper添加注解@MapperScan,编辑dao/UserDOMapper.java

/**
 * 接口中的方法名称要和对应的MyBatis映射文件中的语句的id值一样
 */
@MapperScan
public interface UserDOMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(UserDO record);

    int insertSelective(UserDO record);

    UserDO selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(UserDO record);

    int updateByPrimaryKey(UserDO record);
}

 

(三).方法二(继承SqlSessionDaoSupport,并实现SqlSession接口)

数据库相关bean对象配置,创建resources/spring/applicationContext_database.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- 引入配置文件 -->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:/mybatis/db.properties"/>
    </bean>

    <!-- dataSource配置 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          init-method="init" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>

        <property name="filters" value="log4j"/>
        <property name="maxActive" value="5"/>
        <property name="initialSize" value="1"/>
        <property name="maxWait" value="6000"/>
    </bean>

    <!-- mybatis配置,mapper.xml文件扫描 -->
    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:/mybatis/mybatis.xml"/>
        <property name="mapperLocations" value="classpath:/mybatis/mapper/*Mapper.xml"/>
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

继承SqlSessionDaoSupport,并实现SqlSession接口,创建dao/impl/BaseDaoImpl.java

public class BaseDaoImpl extends SqlSessionDaoSupport implements SqlSession {

    @Override
    @Resource
    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
        super.setSqlSessionFactory(sqlSessionFactory);
    }

    public <T> T selectOne(String s) {
        return getSqlSession().selectOne(s);
    }

    public <T> T selectOne(String s, Object o) {
        return getSqlSession().selectOne(s, o);
    }

    public <E> List<E> selectList(String s) {
        return getSqlSession().selectList(s);
    }

    public <E> List<E> selectList(String s, Object o) {
        return getSqlSession().selectList(s, o);
    }

    public <E> List<E> selectList(String s, Object o, RowBounds rowBounds) {
        return getSqlSession().selectList(s, o, rowBounds);
    }

    public <K, V> Map<K, V> selectMap(String s, String s1) {
        return getSqlSession().selectMap(s, s1);
    }

    public <K, V> Map<K, V> selectMap(String s, Object o, String s1) {
        return getSqlSession().selectMap(s, o, s1);
    }

    public <K, V> Map<K, V> selectMap(String s, Object o, String s1, RowBounds rowBounds) {
        return getSqlSession().selectMap(s, o, s1, rowBounds);
    }

    public <T> Cursor<T> selectCursor(String s) {
        return getSqlSession().selectCursor(s);
    }

    public <T> Cursor<T> selectCursor(String s, Object o) {
        return getSqlSession().selectCursor(s, o);
    }

    public <T> Cursor<T> selectCursor(String s, Object o, RowBounds rowBounds) {
        return getSqlSession().selectCursor(s, o, rowBounds);
    }

    public void select(String s, Object o, ResultHandler resultHandler) {
        getSqlSession().select(s, o, resultHandler);
    }

    public void select(String s, ResultHandler resultHandler) {
        getSqlSession().select(s, resultHandler);
    }

    public void select(String s, Object o, RowBounds rowBounds, ResultHandler resultHandler) {
        getSqlSession().select(s, o, rowBounds, resultHandler);
    }

    public int insert(String s) {
        return getSqlSession().insert(s);
    }

    public int insert(String s, Object o) {
        return getSqlSession().insert(s, o);
    }

    public int update(String s) {
        return getSqlSession().update(s);
    }

    public int update(String s, Object o) {
        return getSqlSession().update(s, o);
    }

    public int delete(String s) {
        return getSqlSession().delete(s);
    }

    public int delete(String s, Object o) {
        return getSqlSession().delete(s, o);
    }

    public void commit() {
        getSqlSession().commit();
    }

    public void commit(boolean b) {
        getSqlSession().commit(b);
    }

    public void rollback() {
        getSqlSession().rollback();
    }

    public void rollback(boolean b) {
        getSqlSession().rollback(b);
    }

    public List<BatchResult> flushStatements() {
        return getSqlSession().flushStatements();
    }

    /**
     * 实现空方法,SqlSession由Spring管理并关闭,如果手工关闭,则会拋异常
     * java.lang.UnsupportedOperationException: Manual close is not allowed over a Spring managed SqlSession
     */
    public void close() {

    }

    public void clearCache() {
        getSqlSession().clearCache();
    }

    public Configuration getConfiguration() {
        return getSqlSession().getConfiguration();
    }

    public <T> T getMapper(Class<T> aClass) {
        return getSqlSession().getMapper(aClass);
    }

    public Connection getConnection() {
        return getSqlSession().getConnection();
    }
}

继承BaseDaoImol,并实现UserDOMapper接口,创建dao/impl/UserDaoImpl.java

@Repository
public class UserDaoImpl extends BaseDaoImpl implements UserDOMapper {
    public int deleteByPrimaryKey(Integer id) {
        return delete("com.learn.spring.server.dao.UserDOMapper.deleteByPrimaryKey", id);
    }

    public int insert(UserDO record) {
        return insert("com.learn.spring.server.dao.UserDOMapper.insert", record);
    }

    public int insertSelective(UserDO record) {
        return insert("com.learn.spring.server.dao.UserDOMapper.insertSelective", record);
    }

    public UserDO selectByPrimaryKey(Integer id) {
        return selectOne("com.learn.spring.server.dao.UserDOMapper.selectByPrimaryKey", id);
    }

    public int updateByPrimaryKeySelective(UserDO record) {
        return update("com.learn.spring.server.dao.UserDOMapper.updateByPrimaryKeySelective", record);
    }

    public int updateByPrimaryKey(UserDO record) {
        return update("com.learn.spring.server.dao.UserDOMapper.updateByPrimaryKey", record);
    }
}

 

(四).调用示例

Spring框架直接注入UserDOMapper,创建service/UserService.java

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserDOMapper userDao;

    public UserDO get(Integer id) {
        return userDao.selectByPrimaryKey(id);
    }
}

 

Spring集成MyBatis框架

标签:hold   close   port   lazyload   xsd   gen   dom   jdbc   resources   

原文地址:http://www.cnblogs.com/faramita2016/p/7512462.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!