1.5JdbcTmeplates、Jpa、Mybatis、beatlsql、Druid的使用
Spring boot 连接数据库整合
-- create table `account`
DROP TABLE `account` IF EXISTS
CREATE TABLE `account` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`money` double DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
INSERT INTO `account` VALUES ('1', 'aaa', '1000');
INSERT INTO `account` VALUES ('2', 'bbb', '1000');
INSERT INTO `account` VALUES ('3', 'ccc', '1000');
在application.properties文件配置mysql的驱动类,数据库地址,数据库账号、密码信息。
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
引入mysql连接类和连接池:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.29</version>
</dependency>
JdbcTemplates访问Mysql
在pom文件引入spring-boot-starter-jdbc的依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
dao
public interface IAccountDAO {
int add(Account account);
int update(Account account);
int delete(int id);
Account findAccountById(int id);
List<Account> findAccountList();
}
class
@Repository
public class AccountDaoImpl implements IAccountDAO {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public int add(Account account) {
return jdbcTemplate.update("insert into account(name, money) values(?, ?)",
account.getName(),account.getMoney());
}
@Override
public int update(Account account) {
return jdbcTemplate.update("UPDATE account SET NAME=? ,money=? WHERE id=?",
account.getName(),account.getMoney(),account.getId());
}
@Override
public int delete(int id) {
return jdbcTemplate.update("DELETE from TABLE account where id=?",id);
}
@Override
public Account findAccountById(int id) {
List<Account> list = jdbcTemplate.query("select * from account where id = ?", new Object[]{id}, new BeanPropertyRowMapper(Account.class));
if(list!=null && list.size()>0){
Account account = list.get(0);
return account;
}else{
return null;
}
}
@Override
public List<Account> findAccountList() {
List<Account> list = jdbcTemplate.query("select * from account", new Object[]{}, new BeanPropertyRowMapper(Account.class));
if(list!=null && list.size()>0){
return list;
}else{
return null;
}
}
}
SpringBoot 整合JPA
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa </artifactId> </dependency>
dao
public interface AccountDao extends JpaRepository<Account,Integer> { }
class
@RestController
@RequestMapping("/account")
public class AccountController {
@Autowired
AccountDao accountDao;
@RequestMapping(value = "/list", method = RequestMethod.GET)
public List<Account> getAccounts() {
return accountDao.findAll();
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public Account getAccountById(@PathVariable("id") int id) {
return accountDao.findOne(id);
}
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public String updateAccount(@PathVariable("id") int id, @RequestParam(value = "name", required = true) String name,
@RequestParam(value = "money", required = true) double money) {
Account account = new Account();
account.setMoney(money);
account.setName(name);
account.setId(id);
Account account1 = accountDao.saveAndFlush(account);
return account1.toString();
}
@RequestMapping(value = "", method = RequestMethod.POST)
public String postAccount(@RequestParam(value = "name") String name,
@RequestParam(value = "money") double money) {
Account account = new Account();
account.setMoney(money);
account.setName(name);
Account account1 = accountDao.save(account);
return account1.toString();
}
}
springboot整合mybatis
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter<artifactId>
<version>1.3.0</version>
</dependency>
dao
@Mapper
public interface AccountMapper {
@Insert("insert into account(name, money) values(#{name}, #{money})")
int add(@Param("name") String name, @Param("money") double money);
@Update("update account set name = #{name}, money = #{money} where id = #{id}")
int update(@Param("name") String name, @Param("money") double money, @Param("id") int id);
@Delete("delete from account where id = #{id}")
int delete(int id);
@Select("select id, name as name, money as money from account where id = #{id}")
Account findAccount(@Param("id") int id);
@Select("select id, name as name, money as money from account")
List<Account> findAccountList();
}
springboot整合 beatlsql
<dependency>
<groupId>com.ibeetl</groupId>
<artifactId>beetl</artifactId>
<version>2.3.2</version>
</dependency>
<dependency>
<groupId>com.ibeetl</groupId>
<artifactId>beetlsql</artifactId>
<version>2.3.1</version>
</dependency>
由于springboot没有对 beatlsql的快速启动装配,所以需要我自己导入相关的bean,包括数据源,包扫描,事物管理器等。
在application加入以下代码:
@Bean(initMethod = "init", name = "beetlConfig")
public BeetlGroupUtilConfiguration getBeetlGroupUtilConfiguration() {
BeetlGroupUtilConfiguration beetlGroupUtilConfiguration = new BeetlGroupUtilConfiguration();
ResourcePatternResolver patternResolver = ResourcePatternUtils.getResourcePatternResolver(new DefaultResourceLoader());
try {
// WebAppResourceLoader 配置root路径是关键
WebAppResourceLoader webAppResourceLoader = new WebAppResourceLoader(patternResolver.getResource("classpath:/templates").getFile().getPath());
beetlGroupUtilConfiguration.setResourceLoader(webAppResourceLoader);
} catch (IOException e) {
e.printStackTrace();
}
//读取配置文件信息
return beetlGroupUtilConfiguration;
}
@Bean(name = "beetlViewResolver")
public BeetlSpringViewResolver getBeetlSpringViewResolver(@Qualifier("beetlConfig") BeetlGroupUtilConfiguration beetlGroupUtilConfiguration) {
BeetlSpringViewResolver beetlSpringViewResolver = new BeetlSpringViewResolver();
beetlSpringViewResolver.setContentType("text/html;charset=UTF-8");
beetlSpringViewResolver.setOrder(0);
beetlSpringViewResolver.setConfig(beetlGroupUtilConfiguration);
return beetlSpringViewResolver;
}
//配置包扫描
@Bean(name = "beetlSqlScannerConfigurer")
public BeetlSqlScannerConfigurer getBeetlSqlScannerConfigurer() {
BeetlSqlScannerConfigurer conf = new BeetlSqlScannerConfigurer();
conf.setBasePackage("com.forezp.dao");
conf.setDaoSuffix("Dao");
conf.setSqlManagerFactoryBeanName("sqlManagerFactoryBean");
return conf;
}
@Bean(name = "sqlManagerFactoryBean")
@Primary
public SqlManagerFactoryBean getSqlManagerFactoryBean(@Qualifier("datasource") DataSource datasource) {
SqlManagerFactoryBean factory = new SqlManagerFactoryBean();
BeetlSqlDataSource source = new BeetlSqlDataSource();
source.setMasterSource(datasource);
factory.setCs(source);
factory.setDbStyle(new MySqlStyle());
factory.setInterceptors(new Interceptor[]{new DebugInterceptor()});
factory.setNc(new UnderlinedNameConversion());//开启驼峰
factory.setSqlLoader(new ClasspathLoader("/sql"));//sql文件路径
return factory;
}
//配置数据库
@Bean(name = "datasource")
public DataSource getDataSource() {
return DataSourceBuilder.create().url("jdbc:mysql://127.0.0.1:3306/test").username("root").password("123456").build();
}
//开启事务
@Bean(name = "txManager")
public DataSourceTransactionManager getDataSourceTransactionManager(@Qualifier("datasource") DataSource datasource) {
DataSourceTransactionManager dsm = new DataSourceTransactionManager();
dsm.setDataSource(datasource);
return dsm;
}
在resouces包下,加META_INF文件夹,文件夹中加入spring-devtools.properties:
restart.include.beetl=/beetl-2.3.2.jar
restart.include.beetlsql=/beetlsql-2.3.1.jar
加入jar和配置beatlsql的这些bean,以及resources这些配置之后,springboot就能够访问到数据库类。
数据访问dao层
public interface AccountDao extends BaseMapper<Account> {
@SqlStatement(params = "name")
Account selectAccountByName(String name);
}
Spring Boot集成Druid实现数据源管理与监控
Druid是阿里开源的一个JDBC应用组件, 其包括三部分:
DruidDriver 代理Driver,能够提供基于Filter-Chain模式的插件体系。
DruidDataSource 高效可管理的数据库连接池。
SQLParser SQL语法分析
通过Druid连接池中间件, 我们可以实现:
可以监控数据库访问性能,Druid内置提供了一个功能强大的StatFilter插件,能够详细统计SQL的执行性能,这对于线上分析数据库访问性能有帮助。
替换传统的DBCP和C3P0连接池中间件。Druid提供了一个高效、功能强大、可扩展性好的数据库连接池。
数据库密码加密。直接把数据库密码写在配置文件中,这是不好的行为,容易导致安全问题。DruidDruiver和DruidDataSource都支持PasswordCallback。
SQL执行日志,Druid提供了不同的LogFilter,能够支持Common-Logging、Log4j和JdkLog,你可以按需要选择相应的LogFilter,监控你应用的数据库访问情况。
扩展JDBC,如果你要对JDBC层有编程的需求,可以通过Druid提供的Filter-Chain机制,很方便编写JDBC层的扩展插件。
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.9</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>
Spring Boot配置文件配置
Spring Boot配置文件有application.properties和application.yml两种配置文件方式 , 此处采用的是application.yml的配置方式。
# Spring Datasource Settings
spring:
datasource:
name: druidDataSource
type: com.alibaba.druid.pool.DruidDataSource
druid:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.202.17:3306/auth_service?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false
username: root
password: 123456
filters: stat,wall,log4j,config
max-active: 100
initial-size: 1
max-wait: 60000
min-idle: 1
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
validation-query: select 'x'
test-while-idle: true
test-on-borrow: false
test-on-return: false
pool-prepared-statements: true
max-open-prepared-statements: 50
max-pool-prepared-statement-per-connection-size: 20
说明:
- spring.datasource.druid.max-active 最大连接数
- spring.datasource.druid.initial-size 初始化大小
- spring.datasource.druid.min-idle 最小连接数
- spring.datasource.druid.max-wait 获取连接等待超时时间
- spring.datasource.druid.time-between-eviction-runs-millis 间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
- spring.datasource.druid.min-evictable-idle-time-millis 一个连接在池中最小生存的时间,单位是毫秒
- spring.datasource.druid.filters=config,stat,wall,log4j 配置监控统计拦截的filters,去掉后监控界面SQL无法进行统计,’wall’用于防火墙
Druid提供以下几种Filter信息:
Filter类名 ===别名
default ===com.alibaba.druid.filter.stat.StatFilter
stat ===com.alibaba.druid.filter.stat.StatFilter
mergeStat ===com.alibaba.druid.filter.stat.MergeStatFilter
encoding ===com.alibaba.druid.filter.encoding.EncodingConvertFilter
log4j ===com.alibaba.druid.filter.logging.Log4jFilter
log4j2 ===com.alibaba.druid.filter.logging.Log4j2Filter
slf4j ===com.alibaba.druid.filter.logging.Slf4jLogFilter
commonlogging ===com.alibaba.druid.filter.logging.CommonsLogFilter
wall ===com.alibaba.druid.wall.WallFilter
1.5JdbcTmeplates、Jpa、Mybatis、beatlsql、Druid的使用的更多相关文章
- spring boot 学习(五)SpringBoot+MyBatis(XML)+Druid
SpringBoot+MyBatis(xml)+Druid 前言 springboot集成了springJDBC与JPA,但是没有集成mybatis,所以想要使用mybatis就要自己去集成. 主要是 ...
- spring + Mybatis + pageHelper + druid 整合源码分享
springMvc + spring + Mybatis + pageHelper + druid 整合 spring 和druid整合,spring 整合druid spring 和Mybatis ...
- Spring Boot 中使用 MyBatis 整合 Druid 多数据源
2017 年 10 月 20 日 Spring Boot 中使用 MyBatis 整合 Druid 多数据源 本文将讲述 spring boot + mybatis + druid 多数据源配置方 ...
- 构建第一个Spring Boot2.0应用之集成mybatis、Druid(七)
一.环境: IDE:IntelliJ IDEA 2017.1.1 JDK:1.8.0_161 Maven:3.3.9 springboot:2.0.2.RELEASE 二.说明: 本文综合之 ...
- SpringBoot 使用yml配置 mybatis+pagehelper+druid+freemarker实例
SpringBoot 使用yml配置 mybatis+pagehelper+druid+freemarker实例 这是一个简单的SpringBoot整合实例 这里是项目的结构目录 首先是pom.xml ...
- 【springboot spring mybatis】看我怎么将springboot与spring整合mybatis与druid数据源
目录 概述 1.mybatis 2.druid 壹:spring整合 2.jdbc.properties 3.mybatis-config.xml 二:java代码 1.mapper 2.servic ...
- 搭建Springboot+mybatis+redis+druid
2019独角兽企业重金招聘Python工程师标准>>> 准备工作 JDK:1.8 使用技术:SpringBoot.Dubbo.Mybatis.Druid 开发工具:Intelj ID ...
- spring jpa + mybatis快速开始:
springmvc开始搭建 源码地址 https://gitee.com/flydb/spingjpamy pom: <packaging>war</packaging> &l ...
- Spring Boot 整合 Mybatis 实现 Druid 多数据源详解
摘要: 原创出处:www.bysocket.com 泥瓦匠BYSocket 希望转载,保留摘要,谢谢! “清醒时做事,糊涂时跑步,大怒时睡觉,独处时思考” 本文提纲一.多数据源的应用场景二.运行 sp ...
- 基于Spring、SpringMVC、MyBatis、Druid、Shrio构建web系统
源码下载地址:https://github.com/shuaijunlan/Autumn-Framework 在线Demo:http://autumn.shuaijunlan.cn 项目介绍 Autu ...
随机推荐
- PCIe - 那点点事
各位看官,这是我拷贝过来的,作为学习笔记(本人对图比较感兴趣,你说我懒也行,上图,这个看着舒服易懂): 1. Wire, lane, link 啥关系 注: PCIe 每条lane有1个双向通道(一个 ...
- I Hate It (HDU 1754)
Problem 很多学校流行一种比较的习惯.老师们很喜欢询问,从某某到某某当中,分数最高的是多少. 这让很多学生很反感. 不管你喜不喜欢,现在需要你做的是,就是按照老师的要求,写一个程序,模拟老师 ...
- gitlab 配置.ssh实现免密登陆
首次配置gitlab的.ssh时 安装gitbash 通过gitbash 配置.ssh 打开gitbash,输入如下命令生成ssh,邮箱换成自己的 ssh-keygen -t rsa -C " ...
- mxnet快速入门教程
前段时间工作中用到了MXnet,然而MXnet的文档写的实在是.....所以在这记录点东西,方便自己,也方便大家. 一.MXnet的安装及使用 开源地址:https://github.com/dmlc ...
- Intellij IDEA导入JAVA项目并启动(哈哈哈,天天都有人问)
最近有很多同学,竟然不知道如何使用Intellij IDEA打开Java项目并启动 现在来讲一下,希望不要忘记了 1.打开IDEA开机页面 Maven项目 2.Maven项目是以pom文件引入各项ja ...
- Swift 可选链
可选链(Optional Chaining)是一种可以请求和调用属性.方法和子脚本的过程,用于请求或调用的目标可能为nil. 可选链返回两个值: 如果目标有值,调用就会成功,返回该值 如果目标为nil ...
- LocalDB数据库修改排序规则,修复汉字变问号
VS中新增的轻量级数据库LocalDB,有个这个,开发人员就不必再安装庞大的SQL server了,可以方便地测试运行小型项目:既然是轻量级数据库,它抛弃了庞大的身躯,功能上当然也会受到局限,其中之一 ...
- 使用badusb“烧鹅”制作“百度U盘”
HID攻击:USB HID攻击技术是一种利用USB接口伪造用户击键行为实施是攻击的方式.通过恶意USB HID设备连接主机后发送伪造的按键命令,篡改系统设置.运行恶意功能.这种技术区别于传统的USB攻 ...
- 阶段5 3.微服务项目【学成在线】_day04 页面静态化_14-页面静态化-数据模型-远程请求接口
okhttp的官方文档: https://square.github.io/okhttp/ github的地址 https://github.com/square/okhttp/ 如何远程请求轮播图的 ...
- spring中的原型模式
大家好,我原本是神剑山庄的铸剑师,名叫小赵,本来干的好好的,后来一时兴起,睡了三少爷的小姨子,与其一直提心吊胆,干脆来个逃之夭夭. 但是,我也要吃饭的呀,工作也得找,神剑山庄去不得,还有断剑山庄.藏剑 ...