springboot_mybatis+druid模板

git地址:https://github.com/wangruyu1/springboot_demo.git 下的springboot.mybatis.demo

springboot环境搭建

  在resources下创建application.yaml,application-dev.yaml,application-datasource-dev.yaml文件.
  application.yaml:

// 这个是最基本的配置文件,会被加载所有属性,通用的属性可以写在这个文件中
spring:
  profiles:
    active: dev
    #表示激活application-dev文件

application-dev.yaml:测试环境相关属性可写在这里

//测试环境配置文件
spring:
  profiles:
    include: 
    #表示加载config/application-datasource-dev,config/application-tomcat文件
    - datasource-dev
    - tomcat

application-datasource-dev.yaml:测试环境的数据源配置文件

//测试环境配置文件
//相关属性解释:https://github.com/alibaba/druid/wiki/DruidDataSource%E9%85%8D%E7%BD%AE%E5%B1%9E%E6%80%A7%E5%88%97%E8%A1%A8
demo:
  datasource:
    url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf8&useSSL=true
    username: root
    password: 
    driverClassName: com.mysql.jdbc.Driver
    filters: stat
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    maxPoolPreparedStatementPerConnectionSize: 20
    spring.datasource.filters: stat,wall,log4j
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

mybatis配置

根据数据库表自动生成mapper,entity,sql文件

  在resources下创建generatorConfig.xml文件,并在pom.xml添加相关插件.
  generatorConfig.xml:

//自动生成表相关文件
<?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>
	<context id="mysql" targetRuntime="MyBatis3">
		<commentGenerator>
			<property name="suppressDate" value="true" />
			<!-- 是否去除自动生成的注释 true:是 : false:-->
			<property name="suppressAllComments" value="true" />
		</commentGenerator>
		<!--数据库链接地址账号密码 -->
		<jdbcConnection driverClass="com.mysql.jdbc.Driver"
			connectionURL="jdbc:mysql://localhost:3306/springboot" userId="root"
			password="">
		</jdbcConnection>
		<javaTypeResolver>
			<property name="forceBigDecimals" value="false" />
		</javaTypeResolver>

		<!--生成Model类存放位置 -->
		<javaModelGenerator targetPackage="com.springboot.mybatis.demo.entity"
			targetProject="src/main/java">
			<property name="enableSubPackages" value="true" />
			<property name="trimStrings" value="true" />
		</javaModelGenerator>
		<!--生成映射文件存放位置 -->
		<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
			<property name="enableSubPackages" value="true" />
		</sqlMapGenerator>
		<!--生成mapper类存放位置 -->
		<javaClientGenerator type="XMLMAPPER"
			targetPackage="com.springboot.mybatis.demo.mapper" targetProject="src/main/java">
			<property name="enableSubPackages" value="true" />
		</javaClientGenerator>
		<!--生成对应表及类名 -->
		<table tableName="user" domainObjectName="User"
			enableCountByExample="false" enableUpdateByExample="false"
			enableDeleteByExample="false" enableSelectByExample="false"
			selectByExampleQueryId="false">
		</table>
	</context>
</generatorConfiguration>

  pom.xml

//mybatis插件以及生成文件时需要的数据库驱动
<plugin>
				<!-- 自动生成mapper,xml文件插件 -->
				<groupId>org.mybatis.generator</groupId>
				<artifactId>mybatis-generator-maven-plugin</artifactId>
				<version>1.3.2</version>
				<configuration>
					<verbose>true</verbose>
					<overwrite>true</overwrite>
				</configuration>
				<dependencies>
					<dependency>
						<groupId>MySQL</groupId>
						<artifactId>mysql-connector-Java</artifactId>
						<version>5.1.38</version>
					</dependency>
				</dependencies>
			</plugin>

  执行maven命令:mybatis-generator:generate,刷新工程,相应的文件即可出现。

mybatis与数据库配置

  DemoDataSourceConfiguration.java

@Configuration
@MapperScan(basePackages = DemoDataSourceConfiguration.MAPPER, sqlSessionFactoryRef = "demoPoiSqlSessionFactory")
public class DemoDataSourceConfiguration {
	private static final Logger LOGGER = LoggerFactory.getLogger(DemoDataSourceConfiguration.class);
	static final String MAPPER = "com.springboot.mybatis.demo.mapper"; // mybatis生成的mapper文件所在的位置
	private static final String XML_MAPPER = "classpath:mapper/*.xml";// mybatis生成的xml文件所在的位置

	/**
	 * 数据源,alibaba的数据源比较强大。
	 * 
	 * @return
	 */
	@Primary
	@Bean(name = "demoPoiDataSource")
	@ConfigurationProperties("demo.datasource") // 该注解可以自动注入对象的属性(对应配置文件demo.datasource下的属性)
	public DruidDataSource demoPoiDataSource() {
		return new DruidDataSource();
	}

	/**
	 * 事务管理
	 * 
	 * @return
	 */
	@Bean(name = "demoPoiTransactionManager")
	@Primary
	public DataSourceTransactionManager demoPoiTransactionManager() {
		return new DataSourceTransactionManager(demoPoiDataSource());
	}

	/**
	 * 工厂类
	 * 
	 * @param dataSource
	 * @return
	 * @throws Exception
	 */
	@Bean(name = "demoPoiSqlSessionFactory")
	@Primary
	public SqlSessionFactory demoPoiSqlSessionFactory(@Qualifier("demoPoiDataSource") DataSource dataSource)
			throws Exception {
		final SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
		sessionFactoryBean.setDataSource(dataSource);
		// 指定扫描的xml路径
		sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(XML_MAPPER));
		return sessionFactoryBean.getObject();
	}

	@Bean(name = "demoPoiSqlSessionTemplate")
	@Primary
	@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON, proxyMode = ScopedProxyMode.TARGET_CLASS)
	public SqlSessionTemplate demoPoiSqlSessionTemplate(
			@Qualifier("demoPoiSqlSessionFactory") SqlSessionFactory demoPoiSqlSessionFactory) {
		SqlSessionTemplate demoPoiSqlSession = new SqlSessionTemplate(demoPoiSqlSessionFactory);
		LOGGER.info("注入demoPoi sqlsession({})成功.", demoPoiSqlSession);
		return demoPoiSqlSession;
	}
}

  具体参数含义看文件内容,结束。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值