无xml实现spring + mybatis

spring + mybatis整合,在现在看来,已经是个古老的话题了。
    但是,网上关于只有spring + mybatis两种框架整合的教程却很少,大部分都是SSM的教程。 
    更不要说,无xml实现的spring + mybatis整合。
很多人看到这句话,会想,那这特喵的跟Spring Boot有毛线区别?
    对,这跟Spring Boot一样,都是无xml整合。但是不一样的是,它很精简。
    它是我为了完成在jar中独立运行而搭建的。昨天搭了纯mybatis的。(PS:用main方法就能调用的方式)。

好吧,废话太多,现在进入正题:
老规矩,项目结构:

无xml实现spring + mybatis_第1张图片

这个类是重点,我在里面写了点注释。
你也可以下载源码自己运行。源码在码云上(点我,快点我㊣)。

【更新】添加tx.mybatis支持,避免写通用的CRUD

package com.spring.build;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;

//import org.mybatis.spring.mapper.MapperScannerConfigurer;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;
//这里换成tk的MapperScannerConfigurer

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.yaml.snakeyaml.Yaml;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.spring.build.entity.User;
import com.spring.build.service.IBaseService;


/**
 * Hello world!
 *
 */
@Configuration
@ComponentScan(basePackages = "com.spring.build.service.impl")
public class App {

    //private static final String[] mapperLocations = {"com.spring.build.mapper"};
    private static final String[] mapperLocations = {"tk.mybatis.mapper.common.base", "com.spring.build.mapper"};
    //增加tk的基础mapper

    private static final String configPath = "config" + File.separator + "qyFramework.yml";

    @Bean
    public DataSource druidDataSource() throws Exception {
        Map configs = loadYaml();
        @SuppressWarnings("unchecked")
        Map druidConfig = (Map) configs.get("druid");
        Map properties  = valueToStr(druidConfig);
        DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
        return dataSource;
    }

    @Bean //将mybatis的所有mapper扫描出来,变成bean
    public MapperScannerConfigurer mapperScanner(SqlSessionFactoryBean sqlSessionFactory) {
        MapperScannerConfigurer mapperScanner = new MapperScannerConfigurer();
        for (String mapperLocation : mapperLocations) {
            mapperScanner.setBasePackage(mapperLocation);
        }
        mapperScanner.setSqlSessionFactoryBeanName("sqlSessionFactory");



        //新增配置:由于项目不需要驼峰转下划线,所以,配置style:normal
        Properties properties = new Properties();
        properties.put("style", "normal");//驼峰不转下划线
        mapperScanner.setProperties(properties);

        return mapperScanner;
    }

    @Bean(name = "mysqlTransactionManager")  //spring接管mybatis的所有mapper bean
    public DataSourceTransactionManager mysqlManager(DataSource dataSource) {  
        return new DataSourceTransactionManager(dataSource);  
    }  

    @Bean //spring-mybatis SqlSessionFactoryBean
            //这里的Configuration里配置mapperLocations,
            //是mybatis扫描mapper和mapper.xml。
            //上面的那个MapperScannerConfigurer mapperScanner是扫描mapper,
            //然后提供给spring.两种是有差别的。
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) throws IOException {
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource);
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        for (String mapperLocation : mapperLocations) {
            configuration.addMappers(mapperLocation);
        }
        sqlSessionFactory.setConfiguration(configuration);
        return sqlSessionFactory;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(SqlSessionFactoryBean sqlSessionFactoryBean) throws Exception {
        return sqlSessionFactoryBean.getObject();
    }

    @SuppressWarnings("resource") //我把测试用例放在了这里。你可以在任何地方执行这一段。
    //打包成jar后,在其他包里也行.
    public static void main( String[] args ) {
        ApplicationContext context = new AnnotationConfigApplicationContext(App.class);
        IBaseService service = context.getBean(IBaseService.class);
        User user = service.queryUserById(10000l);
        System.out.println(user);
    }

    private static Map valueToStr(Map map) {
        Map stringMap = new HashMap();
        for (Entry entry : map.entrySet()) {
            String value = entry.getValue().toString();
            stringMap.put(entry.getKey(), value);
        }
        return stringMap;
    }

    @SuppressWarnings("unchecked")//加载yml文件
    private static Map loadYaml() {
        ClassLoader loader = App.class.getClassLoader();
        URL rootURL = loader.getResource("");
        String rootPath = rootURL.getPath();
        File config = new File(rootPath + File.separator + configPath);
        FileInputStream input = null;
        Map map = null;
        try {
            input = new FileInputStream(config);
            Yaml yaml = new Yaml();
            map = (Map)yaml.load(input);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return map;
    } 
}

你可能感兴趣的:(spring,mybatis)