springboot-27-整合mybatis,druid连接池
sprinboot整合mybatis, 有2种方式, 第一种完全使用注解的方式, 还有一种就是使用xml文件的方式
项目使用gradle + idea, 数据源使用druid, 多使用groovy编写
环境配置
1, 依赖
dependencies {
compile("org.springframework.boot:spring-boot-devtools")
compile("org.springframework.boot:spring-boot-starter")
compile("org.springframework.boot:spring-boot-starter-web")
compile("org.springframework.boot:spring-boot-starter-log4j2")
compile("com.fasterxml.jackson.dataformat:jackson-dataformat-yaml")
compile("org.codehaus.groovy:groovy-all:2.4.11") compile 'mysql:mysql-connector-java'
compile 'com.alibaba:druid-spring-boot-starter:1.1.2'
compile 'org.mybatis.spring.boot:mybatis-spring-boot-starter:1.2.0' compile 'javax.inject:javax.inject:1' testCompile group: 'junit', name: 'junit', version: '4.12'
testCompile("org.springframework.boot:spring-boot-starter-test") }
2, user-schame.sql
在springboot的配置文件中, 增加 schema, 可以在程序启动时创建数据表, 插入数据等操作
SET FOREIGN_KEY_CHECKS=; DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` bigint() NOT NULL AUTO_INCREMENT COMMENT '主键id',
`userName` varchar() DEFAULT NULL COMMENT '用户名',
`passWord` varchar() DEFAULT NULL COMMENT '密码',
`user_sex` varchar() DEFAULT NULL,
`nick_name` varchar() DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT= DEFAULT CHARSET=utf8;
3, application.yml
spring:
profiles:
active: dev http:
encoding:
charset: UTF-
force: true
enabled: true server:
tomcat:
uri-encoding: UTF- ---
# 开发环境
spring:
profiles: dev
datasource:
url: jdbc:mysql://localhost:3306/springboot
username: root
password: root
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
# schema: classpath:user-schema.sql
# data: classpath:user-data.sql server:
context-path: /security
port: ---
# 测试环境配置
spring:
profiles: qa ---
# 生产环境配置
spring:
profiles: prod
4, Main.groovy
package com.wenbronk.security import org.mybatis.spring.annotation.MapperScan
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
/**
* Created by wenbronk on 2017/8/14.
*/
@SpringBootApplication
@MapperScan("com.wenbronk.security.mapper")
class SecurityApplication {
static void main(String[] args) {
SpringApplication.run(SecurityApplication.class)
}
}
5, UserEntity.groovy
package com.wenbronk.security.entity
/**
* Created by wenbronk on 2017/8/14.
*/
class UserEntity {
def id
def userName
def passWord
def userSex
def nickName @Override
public String toString() {
return "UserEntity{" +
"id=" + id +
", userName=" + userName +
", passWord=" + passWord +
", userSex=" + userSex +
", nickName=" + nickName +
'}';
}
}
6, UserSexEnum
package com.wenbronk.security.enums; /**
* Created by wenbronk on 2017/8/14.
*/
public enum UserSexEnum {
MAN,
WOMAN
}
完全使用注解的方式:
1, usermapper
package com.wenbronk.security.mapper; import com.wenbronk.security.entity.UserEntity;
import com.wenbronk.security.enums.UserSexEnum;
import org.apache.ibatis.annotations.*; import java.util.List; /**
* Created by wenbronk on 2017/8/14.
*/
public interface UserMapper { @Select("SELECT * FROM users")
@Results({
@Result(property = "userSex", column = "user_sex", javaType = UserSexEnum.class),
@Result(property = "nickName", column = "nick_name")
})
List<UserEntity> findAll(); @Select("SELECT * FROM users WHERE id = #{id}")
@Results({
@Result(property = "userSex", column = "user_sex", javaType = UserSexEnum.class),
@Result(property = "nickName", column = "nick_name")
})
UserEntity findOne(Long id); @Insert("INSERT INTO users(userName,passWord,user_sex) VALUES(#{userName}, #{passWord}, #{userSex})")
void insert(UserEntity user); @Update("UPDATE users SET userName=#{userName},nick_name=#{nickName} WHERE id =#{id}")
void update(UserEntity user); @Delete("DELETE FROM users WHERE id =#{id}")
void delete(Long id); }
2, 测试类
package com.wenbronk.security.test import com.wenbronk.security.entity.UserEntity
import com.wenbronk.security.enums.UserSexEnum
import com.wenbronk.security.mapper.UserMapper
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner import javax.inject.Inject
/**
* Created by wenbronk on 2017/8/14.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
class MybatisTest { @Inject
UserMapper userMapper; @Test
void insert() {
userMapper.insert(new UserEntity(userName: 'vini', passWord: '', userSex: UserSexEnum.WOMAN, nickName: 'H'))
userMapper.insert(new UserEntity(userName: 'bronk', passWord: '', userSex: UserSexEnum.MAN, nickName: 'H'))
} @Test
void query() {
def find = userMapper.findAll()
println find
} }
更多注解请移步:http://www.mybatis.org/mybatis-3/zh/java-api.html
使用xml的方式
1, application.yml中添加
mybatis.config-locations=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
2, mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias alias="Integer" type="java.lang.Integer" />
<typeAlias alias="Long" type="java.lang.Long" />
<typeAlias alias="HashMap" type="java.util.HashMap" />
<typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
<typeAlias alias="ArrayList" type="java.util.ArrayList" />
<typeAlias alias="LinkedList" type="java.util.LinkedList" />
<package name="com.wenbronk.security.entity"/>
</typeAliases>
</configuration>
3, user的映射文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.wenbronk.security.mapper.UserEntityMapper" >
<resultMap id="BaseResultMap" type="UserEntity" >
<id column="id" property="id" jdbcType="BIGINT" />
<result column="userName" property="userName" jdbcType="VARCHAR" />
<result column="passWord" property="passWord" jdbcType="VARCHAR" />
<result column="user_sex" property="userSex" javaType="com.wenbronk.security.enums.UserSexEnum"/>
<result column="nick_name" property="nickName" jdbcType="VARCHAR" />
</resultMap> <sql id="Base_Column_List" >
id, userName, passWord, user_sex, nick_name
</sql> <select id="getAll" resultMap="BaseResultMap" >
SELECT
<include refid="Base_Column_List" />
FROM users
</select> <select id="getOne" parameterType="java.lang.Long" resultMap="BaseResultMap" >
SELECT
<include refid="Base_Column_List" />
FROM users
WHERE id = #{id}
</select> <insert id="insert" parameterType="UserEntity" >
INSERT INTO
users
(userName,passWord,user_sex)
VALUES
(#{userName}, #{passWord}, #{userSex})
</insert> <update id="update" parameterType="UserEntity" >
UPDATE
users
SET
<if test="userName != null">userName = #{userName},</if>
<if test="passWord != null">passWord = #{passWord},</if>
nick_name = #{nickName}
WHERE
id = #{id}
</update> <delete id="delete" parameterType="java.lang.Long" >
DELETE FROM
users
WHERE
id =#{id}
</delete>
</mapper>
4, dao代码
public interface UserMapper { List<UserEntity> getAll(); UserEntity getOne(Long id); void insert(UserEntity user); void update(UserEntity user); void delete(Long id); }
代码地址: https://github.com/wenbronk/springboot-test/tree/master/security-mybatis/src
druid 的更多配置: https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter
原博客地址: http://blog.csdn.net/gebitan505/article/details/54929287
springboot-27-整合mybatis,druid连接池的更多相关文章
- spring 5.x 系列第6篇 —— 整合 mybatis + druid 连接池 (代码配置方式)
源码Gitub地址:https://github.com/heibaiying/spring-samples-for-all 项目目录结构 1.创建maven工程,除了Spring基本依赖外,还需要导 ...
- spring 5.x 系列第5篇 —— 整合 mybatis + druid 连接池 (xml配置方式)
源码Gitub地址:https://github.com/heibaiying/spring-samples-for-all 项目目录结构 1.创建maven工程,除了Spring基本依赖外,还需要导 ...
- SpringBoot入门篇--整合mybatis+generator自动生成代码+druid连接池+PageHelper分页插件
原文链接 我们这一篇博客讲的是如何整合Springboot和Mybatis框架,然后使用generator自动生成mapper,pojo等文件.然后再使用阿里巴巴提供的开源连接池druid,这个连接池 ...
- springboot整合druid连接池、mybatis实现多数据源动态切换
demo环境: JDK 1.8 ,Spring boot 1.5.14 一 整合durid 1.添加druid连接池maven依赖 <dependency> <groupId> ...
- MyBatis学习-使用Druid连接池将Maybatis整合到spring
目录 前言 什么是Druid连接池 Druid可以做什么? 导入库包 连接oracle 连接mysql 导入mybatis 导入druid 导入spring-jdbc包 导入spring包 导入spr ...
- 使用MyBatis集成阿里巴巴druid连接池(不使用spring)
在工作中发现mybatis默认的连接池POOLED,运行时间长了会报莫名其妙的连接失败错误.因此采用阿里巴巴的Druid数据源(码云链接 ,中文文档链接). mybatis更多数据源参考博客链接 . ...
- springboot+mybatis+druid数据库连接池
参考博客https://blog.csdn.net/liuxiao723846/article/details/80456025 1.先在pom.xml中引入druid依赖包 <!-- 连接池 ...
- spring+mybatis+c3p0数据库连接池或druid连接池使用配置整理
在系统性能优化的时候,或者说在进行代码开发的时候,多数人应该都知道一个很基本的原则,那就是保证功能正常良好的情况下,要尽量减少对数据库的操作. 据我所知,原因大概有这样两个: 一个是,一般情况下系统服 ...
- springboot集成druid连接池
使用druid连接池主要有几步: 1.添加jar和依赖 <groupId>org.mybatis.spring.boot</groupId> <artifactId> ...
随机推荐
- kepware http接口 Objective-C开发
读取某变量的值(NSURL #import <Foundation/Foundation.h> NSDictionary *headers = @{ @"Connection&q ...
- 马士兵 spring 视频笔记
课程内容 1. 面向接口(抽象)编程的概念与好处 2. IOC/DI的概念与好处 a) inversion of control b) dependen ...
- AngularJS config run 及区别和例子
一.config方法 在模块加载阶段,对模块进行自定义配置 config可以注入$stateProvider, $urlRouterProvider, $controllerProvider, $pr ...
- 关于 cxGrid 的过滤问题
http://bbs.csdn.net/topics/390536919 关于 cxGrid 的过滤问题 [问题点数:20分,结帖人zhengyc653] 不显示删除回复 ...
- php开发工具,zendstudio13使用方法补丁
官网原版下载http://downloads.zend.com/studio ... win32.win32.x86.exe 破解补丁:链接:http://pan.baidu.com/s/1gdi4U ...
- poj 2262 Goldbach's Conjecture
素数判定...很简单= =.....只是因为训练题有,所以顺便更~ #include<cstdio> #include<memory.h> #define maxn 50000 ...
- 3.翻译:EF基础系列--EF怎么工作的?
原文链接:http://www.entityframeworktutorial.net/basics/how-entity-framework-works.aspx 这里,你将会大概了解到EF是怎么工 ...
- nodejs 环境配置技巧
环境:Mac OSX 10.10.3 NodeJS:v0.12.2 NodeJs 安装指需要 1.执行 npm install xxxx -g 时 需要执行 sudo npm install xxxx ...
- Android RecycleView 的优化
减少条目的 View 的层级.层级越少效率越高,尤其避免使用 weight.用 ConstraintLayout 可以最大程度减少层级. 使用 ViewStub.如果某个 view 可能不需要被加载, ...
- JSOI2010 缓存交换
题目链接:戳我 考虑一个贪心--就是每次我们都选择队列里面之后最晚加入的元素弹出. 维护一个nxt数组就行了. 特判一下之后不会再加入的元素. 代码如下: #include<iostream&g ...