首页 > 其他分享 >Spring boot Mybatis

Spring boot Mybatis

时间:2022-12-13 21:31:11浏览次数:55  
标签:Spring boot springframework mybatis org Mybatis import com

最近刚接触Spring boot,正是因为他的及简配置方便开发,促使我下定决心要用它把之前写的项目重构,那么问题来了,spring boot怎么整合mybatis呢,下面几个配置类来搞定。

在我的代码当中是实现了数据库读写分离的,所以代码仅做参考,如有需要可以加我微信:benyzhous

【后续更新】

 

1、文件结构

 

 

 

DataBaseConfiguration.java用来获取数据库连接配置信息,配置从application.properties中读取

 

MybatisConfiguration.java也就是MyBatis配置核心入口,构建连接创建SqlSessionFactory

Spring boot Mybatis_java

2、下面直接贴代码,有问题的话可以留言或者加我的微信公众号:cha-baba,或者个人微信号:benyzhous

application.yml 相关配置

 

 

# Server settings  
server:
port:8080
address:localhost

# DATASOURCE
jdbc:
driverClass: com.mysql.jdbc.Driver
useUnicode=true&characterEncoding=utf-8
username: root
password: root

# SPRING PROFILES
spring:
# HTTP ENCODING
http:
encoding.charset: UTF-8
encoding.enable: true
encoding.force: true

# WeiXin Configuration
weixin:
mp:
appid: xx
secret: ee
token: weixin
aeskey:

# MyBatis
mybatis:
typeAliasesPackage: com.modou.**.domain
mapperLocations: classpath:/com/modou/**/mapper/*.xml
configLocation: classpath:/mybatis-config.xml

# LOGGING
logging:
level:
com.ibatis:DEBUG

 

DataBaseConfiguration.java

 

 

 

package com.modou.conf.mybatis;  

import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.alibaba.druid.pool.DruidDataSource;

@Configuration
@EnableTransactionManagement
public class DataBaseConfiguration implements EnvironmentAware {

private RelaxedPropertyResolver propertyResolver;

private static Logger log = LoggerFactory.getLogger(DataBaseConfiguration.class);

@Override
public void setEnvironment(Environment env) {
this.propertyResolver = new RelaxedPropertyResolver(env, "jdbc.");
}

@Bean(name="writeDataSource", destroyMethod = "close", initMethod="init")
@Primary
public DataSource writeDataSource() {
"Configruing Write DataSource");

new DruidDataSource();
"url"));
"driverClassName"));
"username"));
"password"));

return datasource;
}

@Bean(name="readOneDataSource", destroyMethod = "close", initMethod="init")
public DataSource readOneDataSource() {
"Configruing Read One DataSource");

new DruidDataSource();
"url"));
"driverClassName"));
"username"));
"password"));

return datasource;
}

@Bean(name="readTowDataSource", destroyMethod = "close", initMethod="init")
public DataSource readTowDataSource() {
"Configruing Read Two DataSource");

new DruidDataSource();
"url"));
"driverClassName"));
"username"));
"password"));

return datasource;
}


@Bean(name="readDataSources")
public List<DataSource> readDataSources(){
new ArrayList<DataSource>();
dataSources.add(readOneDataSource());
dataSources.add(readTowDataSource());
return dataSources;
}

}

 

 

MyBatisConfiguration.java

 

package com.modou.conf.mybatis;  

import java.util.List;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.plugin.rw.RoundRobinRWRoutingDataSourceProxy;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
*
* 获取第二个数据库的连接信息,在application.yml中配置,并指定特定的前缀
*
*/
@Configuration
@ConditionalOnClass({ EnableTransactionManagement.class, EntityManager.class })
@AutoConfigureAfter({ DataBaseConfiguration.class })
@MapperScan(basePackages={"com.modou.**.mapper","com.github.abel533.entity.mapper"})
public class MybatisConfiguration implements EnvironmentAware{
private static Log logger = LogFactory.getLog(MybatisConfiguration.class);

private RelaxedPropertyResolver propertyResolver;

@Resource(name="writeDataSource")
private DataSource writeDataSource;

@Resource(name="readDataSources")
private List<Object> readDataSources;

@Override
public void setEnvironment(Environment environment) {
this.propertyResolver = new RelaxedPropertyResolver(environment,"mybatis.");
}

@Bean
@ConditionalOnMissingBean
public SqlSessionFactory sqlSessionFactory() {
try {
new SqlSessionFactoryBean();
sessionFactory.setDataSource(roundRobinDataSouceProxy());
sessionFactory.setTypeAliasesPackage(propertyResolver
"typeAliasesPackage"));
sessionFactory
new PathMatchingResourcePatternResolver()
.getResources(propertyResolver
"mapperLocations")));
sessionFactory
new DefaultResourceLoader()
.getResource(propertyResolver
"configLocation")));

return sessionFactory.getObject();
catch (Exception e) {
"Could not confiure mybatis session factory");
return null;
}
}


@Bean
public RoundRobinRWRoutingDataSourceProxy roundRobinDataSouceProxy(){
new RoundRobinRWRoutingDataSourceProxy();
proxy.setWriteDataSource(writeDataSource);
proxy.setReadDataSoures(readDataSources);
"READ");
"WRITE");

return proxy;
}

@Bean
@ConditionalOnMissingBean
public DataSourceTransactionManager transactionManager() {
return new DataSourceTransactionManager(writeDataSource);
}
}

 

 

 

Application.java

 

package com.modou.weixin;  

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import com.modou.weixin.service.HelloWorldService;

/**
* Created by chababa on 15/8/22.
*/
@Configuration
@ComponentScan(basePackages={"com.modou.conf","com.modou.weixin"})
@EnableAutoConfiguration
public class Application implements CommandLineRunner{
@Autowired
HelloWorldService helloWorldService;

public static void main(String[] args) {
class, args);
}

@Override
public void run(String... args) throws Exception {
this.helloWorldService.print());
}

}


 

3、maven pom.xml 相关依赖[我是基于我的多模块依赖,这里只是一个示意],其中配置了jrebel热部署插件,需要搭配jrebel6.2.1

 

 

<?xml version="1.0"?>  
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.modou.weixin</groupId>
<artifactId>weixin-boot-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../weixin-boot-parent</relativePath>
</parent>
<artifactId>weixin-boot-services</artifactId>
<name>weixin-boot-services</name>
<url>http://maven.apache.org</url>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<springloaded.version>1.2.4.RELEASE</springloaded.version>
</properties>

<dependencies>
<dependency>
<groupId>com.modou.weixin</groupId>
<artifactId>weixin-boot-sdk</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.modou.weixin</groupId>
<artifactId>mybatis-plugin-rw</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
</dependency>
</dependencies>

</project>

 



标签:Spring,boot,springframework,mybatis,org,Mybatis,import,com
From: https://blog.51cto.com/u_15147537/5935182

相关文章

  • 我对jeecg-boot项目的理解、使用心得和改进建议
    jeecg-boot是什么?官方介绍JeecgBoot是一款基于代码生成器的低代码开发平台,零代码开发!采用前后端分离架构:SpringBoot2.x,AntDesign&Vue,Mybatis-plus,Shiro,JWT。强大的代码生......
  • 在springboot使用jsp
    在springboot配置jsp环境在pom.xml中添加配置依赖内容如下:<dependency><groupId>org.springframework.boot</groupId><artifactId>sp......
  • springboot上传图片
    springboot上传图片新建一个springboot项目;在java/main/com/ljx创建一个controller.fileController类内容如下:packagecom.ljx.controller;​importorg.spr......
  • SpringMVC-day01
    SpringMVC_day01今日内容理解SpringMVC相关概念完成SpringMVC的入门案例学会使用PostMan工具发送请求和数据掌握SpringMVC如何接收请求、数据和响应结果掌握RESTfu......
  • spring启动时排除注入指定bean
    起因:项目中引用了其他项目的公共包依赖,公共包中有第三方的配置信息(不合理,不规范),导致必须在配置文件中加入这样配置(写了一堆无用的配置信息还容易报错),启动时注入......
  • nginx反向代理部署springboot项目报404无法加载静态资源
    问题:nginx反向代理部署springboot项目报404无法加载静态资源(css,js,jpg,png...)为什么要用反向代理:springboot默认启动端口为8080,如果需要通过域名(不加端口号)直接访问sprin......
  • Java 基于springBoot 上传文件
    @RequestMapping("/uploadFile")@ResponseBodypublicMap<String,Object>uploadFile(@RequestParam(value="file")MultipartFile[]file,HttpServletRequ......
  • java springboot项目树结构递归查询
    记录工作本文记录树结构递归查询,像菜单栏和部门首先需要一张表CREATETABLE`sys_dict`(`id`intNOTNULLAUTO_INCREMENT,`parent_id`intNOTNULL,`name`......
  • java springboot+rabbitmq+websocket 订阅展示
    记录工作需要的依赖<!--fastjson坐标--><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId>......
  • SpringBoot2 静态文件路径与接口路径冲突(相同)解决方案
    事情是这样的,最近接手个项目给它底层从ssm整到springboot2+mp由于之前很多xxx.do请求而我又不想用后缀,所以就得匹配全部后缀或者无后缀(方法有很多方案自行百度)......