LMLPHP后院

springboot mybatis 多数据源配置技术

maybe yes 发表于 2017-08-31 17:19

关于 Java 技术,其实 Java 技术不需要有创造力的人,只需要按部就班,死记硬背就可以。Java 技术已经被大型组织和集团给垄断了,大家用的技术大都是 Oracle,Apache 这些组织的代码,所有的东西都已经实现,所以不需要创造力。有些科学家也会吐槽,说 Java 技术是传教性质的,一旦进入,很难出来。

Java 技术缺少的是什么,是傻逼教程,说好听点,就是手把手教程,怎么建立文件夹,怎么创建文件,怎么复制代码。一个程序员熟练了 Java 技术,也就是熟练了这些,真正框架内部的东西是不可能熟练的,因为量太大,人生苦短。

开始手把手教程,希望帮助到大家。

maven 依赖配置:

<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>1.2.1</version>
</dependency>
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>druid</artifactId>
	<version>1.1.2</version>
</dependency>

mybatis config:

package com.lmlphp.nb.config;


import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = {"com.lmlphp.nb.mybatis.bar.mapper", "com.lmlphp.nb.mybatis.bar.model"}, 
	sqlSessionFactoryRef = "barSqlSessionFactory")
public class MybatisBar {

    @Value("${bar.datasource.url}")
    private String url;

    @Value("${bar.datasource.username}")
    private String user;

    @Value("${bar.datasource.password}")
    private String password;

    @Bean(name = "barDataSource")
    public DataSource barDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean(name = "masterTransactionManager")
    public DataSourceTransactionManager masterTransactionManager() {
        return new DataSourceTransactionManager(barDataSource());
    }

    @Bean(name = "barSqlSessionFactory")
    public SqlSessionFactory barSqlSessionFactory(@Qualifier("barDataSource") DataSource barDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(barDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:mybatis/bar/mapper/*.xml"));
        return sessionFactory.getObject();
    }
}

调用示例:

TestExample testExample = new TestExample();
Test test = testMapper.selectByPrimaryKey(1);

后面就是如何使用 mybatis generator。配置文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <classPathEntry location="/path/to/mysql-connector-java-5.1.41.jar" />

    <context id="DB2Tables" targetRuntime="MyBatis3">
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://192.168.1.122:3306/dbName?useSSL=true&useUnicode=true&characterEncoding=utf-8&autoReconnect=true"
                        userId="root"
                        password="">
        </jdbcConnection>

        <javaTypeResolver >
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <javaModelGenerator targetPackage="com.lmlphp.nb.mybatis.bar.model" targetProject="E:\code\projectName\src\main\java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <sqlMapGenerator targetPackage="mybatis.bar.mapper"  targetProject="E:\code\projectName\src\main\resources">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <javaClientGenerator type="XMLMAPPER" targetPackage="com.lmlphp.nb.mybatis.bar.mapper"  targetProject="E:\code\projectName\src\main\java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>

        <table schema="" tableName="test" domainObjectName="Test">
            <property name="useActualColumnNames" value="true"/>
            <generatedKey column="ID" sqlStatement="MySql" identity="true" />
            <!--<columnOverride column="DATE_FIELD" property="startDate" />
            <ignoreColumn column="FRED" />
            <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" />-->
        </table>

    </context>
</generatorConfiguration>

生成代码示例:

java -jar mybatis-generator-core-1.3.5.jar -configfile src\main\resources\mybatis\MBG-bar.xml

SpringBoot 是用来做微服务的,原则上不应该配置多数据源。

相关文章
LMLPHP,可爱滴WEB开发框架

2017-11-19 05:37:55 1511041075 0.004351