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连接池的更多相关文章

  1. spring 5.x 系列第6篇 —— 整合 mybatis + druid 连接池 (代码配置方式)

    源码Gitub地址:https://github.com/heibaiying/spring-samples-for-all 项目目录结构 1.创建maven工程,除了Spring基本依赖外,还需要导 ...

  2. spring 5.x 系列第5篇 —— 整合 mybatis + druid 连接池 (xml配置方式)

    源码Gitub地址:https://github.com/heibaiying/spring-samples-for-all 项目目录结构 1.创建maven工程,除了Spring基本依赖外,还需要导 ...

  3. SpringBoot入门篇--整合mybatis+generator自动生成代码+druid连接池+PageHelper分页插件

    原文链接 我们这一篇博客讲的是如何整合Springboot和Mybatis框架,然后使用generator自动生成mapper,pojo等文件.然后再使用阿里巴巴提供的开源连接池druid,这个连接池 ...

  4. springboot整合druid连接池、mybatis实现多数据源动态切换

    demo环境: JDK 1.8 ,Spring boot 1.5.14 一 整合durid 1.添加druid连接池maven依赖 <dependency> <groupId> ...

  5. MyBatis学习-使用Druid连接池将Maybatis整合到spring

    目录 前言 什么是Druid连接池 Druid可以做什么? 导入库包 连接oracle 连接mysql 导入mybatis 导入druid 导入spring-jdbc包 导入spring包 导入spr ...

  6. 使用MyBatis集成阿里巴巴druid连接池(不使用spring)

    在工作中发现mybatis默认的连接池POOLED,运行时间长了会报莫名其妙的连接失败错误.因此采用阿里巴巴的Druid数据源(码云链接 ,中文文档链接). mybatis更多数据源参考博客链接 . ...

  7. springboot+mybatis+druid数据库连接池

    参考博客https://blog.csdn.net/liuxiao723846/article/details/80456025 1.先在pom.xml中引入druid依赖包 <!-- 连接池 ...

  8. spring+mybatis+c3p0数据库连接池或druid连接池使用配置整理

    在系统性能优化的时候,或者说在进行代码开发的时候,多数人应该都知道一个很基本的原则,那就是保证功能正常良好的情况下,要尽量减少对数据库的操作. 据我所知,原因大概有这样两个: 一个是,一般情况下系统服 ...

  9. springboot集成druid连接池

    使用druid连接池主要有几步: 1.添加jar和依赖 <groupId>org.mybatis.spring.boot</groupId> <artifactId> ...

随机推荐

  1. SVN代码管理发布

    1.svn的独立模式应用 2.svn钩子的应用(例如:代码提交前的文件格式限制,大小限制,代码发布svn成功后的备份等等) 3.大型企业的代码发布流程 有一些制度流程.逻辑方案 4.业务变更管理

  2. 封装了三个对TMemoryStream操作的函数,大牛莫笑

    // TMemoryStream 转化为string字符串 function MemoryStreamToString(M: TMemoryStream): AnsiString; begin Set ...

  3. fastscript例子一

    fastscript例子一   fastscript例子一 unit Unit1; interface usesWinapi.Windows, Winapi.Messages, System.SysU ...

  4. NW.js安装原生node模块node-printer控制打印机

    1.安装原生node模块 #全局安装nw-gyp npm install -g nw-gyp #设置目标NW.js版本 set npm_config_target=0.31.4 #设置构建架构,ia3 ...

  5. c#中的几种Dialog

    1.OpenFileDialog private void FileOpen_Click(object sender, EventArgs e) { OpenFileDialog openFile = ...

  6. XAML 调试工具 不见了?

    XAML调试工具不见了怎么办? 1.调试---> 选项---> 选中 启用XAML的UI调试工具 2.调试---> 选项---> 禁用 使用托管兼容模式 欧了!

  7. MVC和WEBAPI(一)

    什么是MVC (模型 视图 控制器)? MVC是一个架构模式,它分离了表现与交互.它被分为三个核心部件:模型.视图.控制器.下面是每一个部件的分工: 视图是用户看到并与之交互的界面. 模型表示业务数据 ...

  8. AJPFX:外汇的价格图表类型和技术指标类型

    AJPFX:价格图表的类型 柱状图 它是反映价格行为的一种最基本的图表.每一根柱代表一段时间——最短为1分钟,最长为数年.随着时间的推移,柱状图反映出不同的价格形态. 蜡烛图 不同于简单的柱状图,蜡烛 ...

  9. Speech Synthesis

    <Window x:Class="Synthesizer.MainWindow" xmlns="http://schemas.microsoft.com/winfx ...

  10. <转>php中heredoc与nowdoc的使用方法

    http://www.361way.com/php-heredoc-nowdoc/3008.html 一.heredoc结构及用法 Heredoc 结构就象是没有使用双引号的双引号字符串,这就是说在 ...