[六]SpringBoot 之 连接数据库(mybatis)
在进行配置之前首先要了解springboot是如何使用纯java代码方式初始化一个bean的
以前的版本是在xml中使用beans标签,在其里面配置bean,那么纯Java代码怎么实现呢?
答案就是使用@Configuration注解和@Bean,代码如下:当然搜资料过程中你会学习到其他的知识,并尝试使用
1.mybatis-spring-boot-stater的Maven依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency> <dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
</dependency>
2.配置数据源,这里使用的dbcp的数据源,具体大家可以看自己的情况来使用
在src/main/resource中,添加一个application.properties配置文件,这里面添加了一些数据库连接的信息
########################################################
###datasource
########################################################
spring.datasource.url = jdbc:mysql://123.206.228.200:3306/test
spring.datasource.username = shijunjie
spring.datasource.password = ******
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.max-active=20
spring.datasource.max-idle=8
spring.datasource.max-maxWait=100
spring.datasource.min-idle=8
spring.datasource.initial-size=10
2.1注入数据源
package me.shijunjie.config; import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource; @Configuration
@PropertySource("classpath:application.properties")
public class DataSourceConfiguration {
@Value("${spring.datasource.driverClassName}")
private String driver;
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.username}")
private String username;
@Value("${spring.datasource.password}")
private String password;
@Value("${spring.datasource.max-active}")
private int maxActive;
@Value("${spring.datasource.max-idle}")
private int maxIdel;
@Value("${spring.datasource.max-maxWait}")
private long maxWait; @Bean
public BasicDataSource dataSource(){
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setMaxActive(maxActive);
dataSource.setMaxIdle(maxIdel);
dataSource.setMaxWait(maxWait);
dataSource.setValidationQuery("SELECT 1");
dataSource.setTestOnBorrow(true);
return dataSource;
}
}
2.2MyBatis的配置
package me.shijunjie.config; import javax.sql.DataSource; import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
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.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer; @Configuration
//加上这个注解,使得支持事务
@EnableTransactionManagement
public class MybatisConfig implements TransactionManagementConfigurer {
@Autowired
private DataSource dataSource; @Override
public PlatformTransactionManager annotationDrivenTransactionManager() {
return new DataSourceTransactionManager(dataSource);
} @Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactoryBean() {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
try {
return bean.getObject();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
} @Bean
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
2.3配置MyBatis配置文件的路径,这个配置需要与上面的配置分开来写,因为它们有着一个先后顺序
package me.shijunjie.config; import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; @Configuration
@AutoConfigureAfter(MybatisConfig.class)
public class MyBatisMapperScannerConfig {
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
//获取之前注入的beanName为sqlSessionFactory的对象
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
//指定xml配置文件的路径
mapperScannerConfigurer.setBasePackage("me.shijunjie.dao");
return mapperScannerConfigurer;
}
}
2.4使用@Mapper注解来标识一个接口为MyBatis的接口,MyBatis会自动寻找这个接口
package me.shijunjie.dao; import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper; import me.shijunjie.entity.Demo2; @Mapper
public interface DemoDao2{ @Insert("insert into t_demo(tname) "+
"values(#{name})")
int save(Demo2 demo);
}
3.编写Controller 和 Service 以及实体类
编写实体类:
package me.shijunjie.entity;
public class Demo2 {
public Demo2() {
}
public Demo2(long id, String name) {
this.id = id;
this.name = name;
}
private long id;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
编写service和实现类:
package me.shijunjie.service;
import me.shijunjie.entity.Demo2;
public interface DemoService {
public void save(Demo2 demo);
}
package me.shijunjie.service.impl; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import me.shijunjie.dao.DemoDao2;
import me.shijunjie.entity.Demo2;
import me.shijunjie.service.DemoService; @Service
public class DemoServiceImpl implements DemoService { @Autowired
private DemoDao2 demoDao; public void save(Demo2 demo){
demoDao.save(demo);
}
}
编写Controller
package me.shijunjie.controller; import javax.annotation.Resource; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import me.shijunjie.entity.Demo2;
import me.shijunjie.service.DemoService; @RestController
@RequestMapping("/demo")
public class DemoController { @Resource
private DemoService demoService; /** * 测试保存数据方法. * @return */ @RequestMapping("/save")
public String save(){
Demo2 d = new Demo2();
d.setName("Angel2");
demoService.save(d);//保存数据.
return "ok.DemoController.save"; }
}
编写入口类
package me.shijunjie.controller; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling; @ComponentScan(basePackages={"me.shijunjie"}) // 扫描该包路径下的所有spring组件
/*@EnableJpaRepositories("me.shijunjie.dao") // JPA扫描该包路径下的Repositorie
*//*@EntityScan("me.shijunjie.entity") // 扫描实体类
*/@SpringBootApplication
@EnableScheduling
public class App extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
测试
打开浏览器输入http://localhost:8080/demo/save


成功
[六]SpringBoot 之 连接数据库(mybatis)的更多相关文章
- SpringBoot入门 (六) 数据库访问之Mybatis
本文记录学习在SpringBoot中使用Mybatis. 一 什么是Mybatis MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 ...
- Spring Boot(六):如何使用mybatis
Spring Boot(六):如何使用mybatis orm框架的本质是简化编程中操作数据库的编码,发展到现在基本上就剩两家了,一个是宣称可以不用写一句SQL的hibernate,一个是可以灵活调试动 ...
- 转-spring-boot 注解配置mybatis+druid(新手上路)-http://blog.csdn.net/sinat_36203615/article/details/53759935
spring-boot 注解配置mybatis+druid(新手上路) 转载 2016年12月20日 10:17:17 标签: sprinb-boot / mybatis / druid 10475 ...
- 【SpringBoot】11.Springboot整合SpringMVC+Mybatis(上)
Springboot整合SpringMVC+Mybatis 需求分析:通过使用Springboot+SpringMVC+Mybatis 整合实现一个对数据库表users表的CRUD操作. 1.创建项目 ...
- SpringBoot中关于Mybatis使用的三个问题
SpringBoot中关于Mybatis使用的三个问题 转载请注明源地址:http://www.cnblogs.com/funnyzpc/p/8495453.html 原本是要讲讲PostgreSQL ...
- SpringBoot之整合Mybatis范例
依赖包: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http:/ ...
- springboot中使用mybatis显示执行sql
springboot 中使用mybatis显示执行sql的配置,在properties中添加如下 logging.你的包名=debug 2018-11-27 16:35:43.044 [DubboSe ...
- SpringBoot添加对Mybatis分页插件PageHelper的支持
1.修改maven配置文件pom.xml,添加对pageHelper的支持: <!--pagehelper--> <dependency> <groupId>com ...
- SpringBoot添加对Mybatis的支持
1.修改maven配置文件pom.xml,添加对mybatis的支持: <dependency> <groupId>org.mybatis.spring.boot</gr ...
随机推荐
- PHPStrom 里修改Emmet对php的自动扩展
PHPStrom 7.1.3 Emmet 想必大家都比较清楚了.Emmet有个特点,对于匹配不到的符号,仍然会自动扩展为标签的形式,比如我输入aaaa,然后按tab,会自动扩展为<aaaa> ...
- Java SE教程
第0讲 开山篇 读前介绍:本文中如下文本格式是超链接,可以点击跳转 >>超链接<< 我的学习目标:基础要坚如磐石 代码要十份规范 笔记要认真详实 一.java内容介绍 ...
- 二、Django用户认证之cookie和session
1.cookie原理 Cookie意为“甜饼”,是由W3C组织提出,最早由Netscape社区发展的一种机制.目前Cookie已经成为标准,所有的主流浏览器如IE.Netscape.Firefox.O ...
- 开源工具 | 手游自动化框架GAutomator,新增iOS系统和UE4引擎支
WeTest 导读 GAutomator是腾讯WeTest推出的手游自动化测试框架,已用于腾讯多个手游项目组的自动化测试. 1.GAutomator诞生背后 研究过手游自动化测试的同学都知道,虽然市场 ...
- 一起来做chrome扩展《页面右键菜单》
本文主要内容 contextMenus的设置 打开权限 创建菜单 点击菜单 background script向content script发送消息 1. contextMenus的设置 1.1 打开 ...
- C# TTS-文本转语音
System.Speech 命名空间包含支持语音识别的类型,你可以从Visual Studio很方便的添加相关组件的引用. System.Speech相关介绍:https://msdn.microso ...
- TPO-17 C2 Reschedule part-time job in campus dining hall
TPO-17 C2 Reschedule part-time job in campus dining hall 第 1 段 1.Listen to a conversation between a ...
- Docker入门与实践之 docker安装与了解
一.Docker 概述 Docker 是一个开源的应用容器引擎,基于 Go 语言 并遵从Apache2.0协议开源.Docker 可以让开发者打包他们的应用以及依赖包到一个轻量级.可移植的容器中,然后 ...
- MySQL Proxy和 Amoeba 工作机制浅析
MySQL Proxy处于客户端应用程序和MySQL服务器之间,通过截断.改变并转发客户端和后端数据库之间的通信来实现其功能,这和WinGate 之类的网络代理服务器的基本思想是一样的.代理服务器是和 ...
- DotNetOpenAuth Part 1 : Authorization 验证服务实现及关键源码解析
DotNetOpenAuth 是 .Net 环境下OAuth 开源实现框架.基于此,可以方便的实现 OAuth 验证(Authorization)服务.资源(Resource)服务.针对 DotNet ...