1. 导入依赖的jar包

springboot项目整合mybatis之前首先要导入依赖的jar包,配置pom.xml文件如下:

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0

com.u

springboot-mybatis

1.0-SNAPSHOT

org.springframework.boot

spring-boot-starter-parent

1.3.0.RELEASE

com.us.Application

3.2.7

1.2.2

1.8

1.8

org.springframework.boot

spring-boot-starter-web

mysql

mysql-connector-java

6.0.5

com.mchange

c3p0

0.9.5.2

commons-logging

commons-logging

org.springframework

spring-jdbc

org.mybatis

mybatis

${mybatis.version}

org.mybatis

mybatis-spring

${mybatis-spring.version}

org.apache.commons

commons-lang3

3.4

2. 配置数据源

pom.xml配置完毕后需要配置数据源了。新建DBConfig类配置数据源,代码如下:

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.core.env.Environment;

import com.alibaba.druid.pool.DruidDataSource;

import com.google.common.base.Preconditions;

@Configuration

public class DBConfig {

@Autowired

private Environment env;

@Bean(name = "dataSource")

public DruidDataSource dataSource() {

final String url = Preconditions.checkNotNull(env.getProperty("ms.db.url"));

final String username = Preconditions.checkNotNull(env.getProperty("ms.db.username"));

final String password = env.getProperty("ms.db.password");

final int maxActive = Integer.parseInt(env.getProperty("ms.db.maxActive", "200"));

DruidDataSource dataSource = new DruidDataSource();

dataSource.setUrl(url);

dataSource.setUsername(username);

dataSource.setPassword(password);

dataSource.setMaxActive(maxActive);

return dataSource;

}

}

3. 添加数据库连接信息

在配置文件application.properties中添加数据库连接信息如下:

ms.db.url=jdbc:mysql://localhost:3306/dev?prepStmtCacheSize=517&cachePrepStmts=true&autoReconnect=true&characterEncoding=utf-8&allowMultiQueries=true

ms.db.username=root

ms.db.password=admin

ms.db.maxActive=500

4. 配置mybatis的SqlSessionFactoryBean

数据源配置完以后要配置mybatis的SqlSessionFactoryBean进行扫描mapper,新建MyBatisConfig类代码如下(classpath*:mapper/*.xml为mapper.xml文件路径):

import javax.sql.DataSource;

import org.mybatis.spring.SqlSessionFactoryBean;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.ApplicationContext;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

@Configuration

public class MyBatisConfig {

@Autowired

private DataSource dataSource;

@Bean(name = "sqlSessionFactory")

public SqlSessionFactoryBean sqlSessionFactory(ApplicationContext applicationContext) throws Exception {

SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();

sessionFactory.setDataSource(dataSource);

sessionFactory.setMapperLocations(applicationContext.getResources("classpath*:mapper/*.xml"));

return sessionFactory;

}

}

5. 配置MapperScannerConfigurer扫描dao层

然后配置MapperScannerConfigurer扫描dao层,新建类MyBatisScannerConfig代码如下(注意与MyBatisConfig不要写在一个类里):

import org.mybatis.spring.mapper.MapperScannerConfigurer;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

@Configuration

public class MyBatisScannerConfig {

@Bean

public MapperScannerConfigurer MapperScannerConfigurer() {

MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();

mapperScannerConfigurer.setBasePackage("com.example.*.dao");

mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");

return mapperScannerConfigurer;

}

}

6. 开启数据库事务(必须)代码如下

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import org.springframework.transaction.PlatformTransactionManager;

import org.springframework.transaction.annotation.TransactionManagementConfigurer;

@Configuration

public class TransactionConfig implements TransactionManagementConfigurer{

@Autowired

private DataSource dataSource;

@Bean(name = "transactionManager")

@Override

public PlatformTransactionManager annotationDrivenTransactionManager() {

return new DataSourceTransactionManager(dataSource);

}

}

7. 实战

配置大致就是如此,然后就是新建java bean(省略,文章底部有源码地址)

新建mapper.xml文件(省略,文章底部有源码地址,关于mapper.xml 文件编写的疑问可以看我以前的springmvc+mybatis 系列文章)

新建dao层。代码如下:

import java.util.List;

import java.util.Map;

import com.example.base.model.User;

import com.example.config.MyBatisRepository;

public interface UserDao {

public List getList(Map map);

}

service层要在实现类上添加@service注解,代码如下:

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import com.example.base.dao.UserDao;

import com.example.base.service.UserService;

@Service

public class UserServiceImpl implements UserService {

@Autowired

private UserDao userDao;

public Object getList(Map map) {

return userDao.getList(map);

}

}

controller层也要加@controller注解代码如下:

import javax.servlet.http.HttpServletRequest;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.HttpStatus;

import org.springframework.http.ResponseEntity;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.ResponseBody;

import com.example.base.service.UserService;

import com.example.base.util.CommonUtil;

import com.example.demo.ServiceEmail;

@Controller

@RequestMapping(value = "/users")

public class UserController {

@Autowired

private UserService userService;

@Autowired

private ServiceEmail serviceEmail;

/***

* api :localhost:8099/users?id=99 localhost:8099/users

*

* @param request

* @return

*/

@RequestMapping(method = RequestMethod.GET, produces = "application/json;charset=UTF-8")

@ResponseBody

public ResponseEntity> list(HttpServletRequest request) {

Map map = CommonUtil.getParameterMap(request);

return new ResponseEntity(userService.getList(map), HttpStatus.OK);

}

}

然后在启动入口类中扫描定义的这些配置累(配置包名可却省只写部分包名)如下:

import java.util.Arrays;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.boot.builder.SpringApplicationBuilder;

import org.springframework.boot.context.web.SpringBootServletInitializer;

import org.springframework.context.ApplicationContext;

import org.springframework.context.annotation.ComponentScan;

import org.springframework.scheduling.annotation.EnableScheduling;

@ComponentScan(basePackages ="com.example")

@SpringBootApplication

public class Application extends SpringBootServletInitializer{

@Override

protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {

return application.sources(Application.class);

}

public static void main(String[] args) throws Exception {

ApplicationContext ctx = SpringApplication.run(Application.class, args);

String[] beanNames = ctx.getBeanDefinitionNames();

Arrays.sort(beanNames);

for (String beanName : beanNames) {

System.out.println(beanName);

}

}

}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对脚本之家的支持。如果你想了解更多相关内容请查看下面相关链接

dao加service加mysql实例_SpringBoot项目整合mybatis的方法步骤与实例相关推荐

  1. springboot项目整合mybatis

    SpringBoot项目整合mybatis 本章内容 使用 idea创建 SpringBoot项目 SpringBoot项目中配制 mybatis 框架 1 创建 SpringBoot项目 1.1 在 ...

  2. spring项目如何升级mysql包_SpringBoot项目版本升级:从1.5.3升级到2.1.8版本

    SpringBoot项目版本升级:从1.5.3升级到2.1.8版本 前言 简单记录一次本人在自己的SpringBoot项目project-template中,把1.5.3版本升级到2.1.8版本时升级 ...

  3. pom 导入mysql连接,maven项目中的jdbc连接步骤

    在maven项目pom.xml中到入驱动包(以下是驱动包代码) mysql mysql-connector-java 8.0.15 导入成功会看到Maven Dependencies下有个mysql- ...

  4. 通用返回_Springboot项目整合通用mapper

    1.简介 什么是通用mapper 什么是通用mapper,用一句话概括就是,它就是一个辅助mybatis开发的组件,它不是替代mybatis,而是使mybatis更方便的开发.通用mapper提供极其 ...

  5. php mysql or_mysql条件查询and or使用方法及优先级实例分析

    本文实例讲述了mysql条件查询and or使用方法及优先级.分享给大家供大家参考,具体如下: mysql and与or介绍 AND 和 OR 可在 WHERE 子语句中把两个或多个条件结合起来. 使 ...

  6. java redis缓存实例_spring项目整合ehcache和redis缓存实例

    项目描述 Spring的缓存机制非常灵活,可以对容器中任意Bean或者Bean的方法进行缓存,因此这种缓存机制可以在JavaEE应用的任何层次上进行缓存. Spring缓存底层也是需要借助其他缓存工具 ...

  7. mysql+xml+注释,springboot整合mybatis完整示例, mapper注解方式和xml配置文件方式实现(我们要优雅地编程)...

    一.注解方式 pom org.mybatis.spring.boot mybatis-spring-boot-starter 2.0.0 mysql mysql-connector-java org. ...

  8. python中什么是实例-在Python中使用’__rsub__’方法的典型实例是什么?

    基本示例.您编写自己的类似int的类: class FooInt: ... other stuff elided ... def __sub__(self, other): if isinstance ...

  9. phpstudy mysql 版本_phpStudy中升级MySQL版本到5.7.17的方法步骤

    前言 今天在工作发现一个错误,在往本地导数据表的时候老是报错: [Err] 1294 - Invalid ON UPDATE clause for '字段名' column 报错的数据表字段: `字段 ...

最新文章

  1. iptables配置-Linux系统安全防火墙
  2. Keil 汇编窗口无法设置断点,disassembly显示错误,Keil汇编解析错误
  3. macos自带java_在 MacOS 上安装 Java - Java 入门教程
  4. linux向上翻页_linux学习基础篇——文件管理(一)
  5. 《Java核心技术 卷Ⅱ 高级特性(原书第10版)》一2.2.2 如何读入文本输入
  6. Apache Log4j2远程代码执行漏洞攻击,华为云安全支持检测拦截
  7. 【kafka】kafka 脚本 kafka-run-class.sh 使用介绍 jmx监控 查看jmx信息
  8. 【Qt串口调试助手】1.0 - 400行代码撸一个Qt5串口调试助手框架
  9. golang读取文件编码转换问题
  10. 解决LDAP客户端统一认证DirectoryEntry出现 Ox80005000的问题
  11. 疯狂Java讲义(一)
  12. 计算机桌面比例怎么调,如何调整计算机显示器的比例
  13. PIE框架基本接口使用方法
  14. Java 解析xml 使用SAXReader获取所有标签的key和value的代码实例
  15. java object 是否为null,java – 为什么cast(Object)null结果为null?
  16. 智慧工地无线覆盖重点产品人员定位和移动考勤
  17. JavaEE学习路线(经典必看)
  18. 使用 JavaScript 获取当前 URL?
  19. 微博抽奖贴为什么到时间了不开奖_按这6个步骤做抽奖,微博涨粉翻10倍都不止...
  20. Latex 字符集大全

热门文章

  1. python导入csv文件-jupyter 导入csv文件方式
  2. 如何用python创建一个下载网站-如何写一个python脚本下载文件??
  3. python能做什么游戏ll-Python 应该怎么学?
  4. python100个必背知识-学Python必背的初级单词,你都背了吗?
  5. python语言简介-Python语言介绍
  6. python和c哪个好学-c语言和python哪个容易
  7. python基础代码-python基础,python基础代码大全
  8. python怎么导入时间-python初步学习-import和datetime模块
  9. python3下载慢-PIP 下载慢,给你Python3的pip换个源 一键换源
  10. java好还是python好-Python和Java该如何选择?选哪个好?