Spring boot之MyBatis
文章目录
1. 环境依赖
2. 数据源
2.1. 方案一 使用 Spring Boot 默认配置
2.2. 方案二 手动创建
3. 脚本初始化
4. MyBatis整合
4.1. 方案一 通过注解的方式
4.1.1. 实体对象
4.1.2. DAO相关
4.1.3. Service相关
4.1.4. Controller相关
4.2. 方案二 通过配置文件的方式
4.2.1. 实体对象
4.2.2. 配置相关
4.2.3. DAO相关
4.2.4. Service相关
4.2.5. Controller相关
5. 总结
本文讲解Spring Boot基础下,如何整合MyBatis框架,编写数据访问。
环境依赖
修改 POM 文件,添加mybatis-spring-boot-starter依赖。
值得注意的是,可以不添加spring-boot-starter-jdbc。
因为,mybatis-spring-boot-starter依赖中存在spring-boot-starter-jdbc。
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.</version>
</dependency>
添加mysql依赖。
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.</version>
</dependency>
数据源
方案一 使用 Spring Boot 默认配置
在 src/main/resources/application.properties 中配置数据源信息。
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3307/springboot_db?useUnicode = true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
spring.datasource.username=root
spring.datasource.password=root
方案二 手动创建
在 src/main/resources/config/source.properties 中配置数据源信息。
# mysql
source.driverClassName = com.mysql.jdbc.Driver
source.url = jdbc:mysql://localhost:3306/springboot_db?useUnicode = true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
source.username = root
source.password = root
通过 Java Config 创建 dataSource 和jdbcTemplate 。
@Configuration
@EnableTransactionManagement
@PropertySource(value = {"classpath:config/source.properties"})
public class BeanConfig { @Autowired
private Environment env; @Bean(destroyMethod = "close")
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(env.getProperty("source.driverClassName").trim());
dataSource.setUrl(env.getProperty("source.url").trim());
dataSource.setUsername(env.getProperty("source.username").trim());
dataSource.setPassword(env.getProperty("source.password").trim());
return dataSource;
} @Bean
public JdbcTemplate jdbcTemplate() {
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource());
return jdbcTemplate;
}
}
脚本初始化
先初始化需要用到的SQL脚本。
CREATE DATABASE /*!32312 IF NOT EXISTS*/`springboot_db` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `springboot_db`; DROP TABLE IF EXISTS `t_author`; CREATE TABLE `t_author` (
`id` bigint() unsigned NOT NULL AUTO_INCREMENT COMMENT '用户ID',
`real_name` varchar() NOT NULL COMMENT '用户名称',
`nick_name` varchar() NOT NULL COMMENT '用户匿名',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT= DEFAULT CHARSET=utf8;
MyBatis整合
方案一 通过注解的方式
实体对象
package com.boot.mybatis.entity;
import com.alibaba.fastjson.annotation.JSONField;
public class Author {
private Long id;
@JSONField(name="real_name")
private String realName;
@JSONField(name="nick_name")
private String nickName;
// SET和GET方法
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
}
DAO相关
package com.boot.mybatis.dao; import java.util.List; import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update; import com.boot.mybatis.entity.Author; @Mapper
public interface AuthorMapper { @Insert("insert into t_author(real_name, nick_name) values(#{real_name}, #{nick_name})")
int add(@Param("real_name") String realName, @Param("nick_name") String nickName); @Update("update t_author set real_name = #{real_name}, nick_name = #{nick_name} where id = #{id}")
int update(@Param("real_name") String realName, @Param("nick_name") String nickName, @Param("id") Long id); @Delete("delete from t_author where id = #{id}")
int delete(Long id); @Select("select id, real_name as realName, nick_name as nickName from t_author where id = #{id}")
Author findAuthor(@Param("id") Long id); @Select("select id, real_name as realName, nick_name as nickName from t_author")
List<Author> findAuthorList();
}
Service相关
package com.boot.mybatis.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import com.boot.mybatis.dao.AuthorMapper;
import com.boot.mybatis.entity.Author; @Service
public class AuthorService { @Autowired
private AuthorMapper authorMapper; public int add(String realName, String nickName) {
return this.authorMapper.add(realName, nickName);
} public int update(String realName, String nickName, Long id) {
return this.authorMapper.update(realName, nickName, id);
} public int delete(Long id) {
return this.authorMapper.delete(id);
} public Author findAuthor(Long id) {
return this.authorMapper.findAuthor(id);
} public List<Author> findAuthorList() {
return this.authorMapper.findAuthorList();
}
}
Controller相关
为了展现效果,我们先定义一组简单的 RESTful API 接口进行测试。
package com.boot.mybatis.controller; import java.util.HashMap;
import java.util.List;
import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; import com.boot.mybatis.entity.Author;
import com.boot.mybatis.service.AuthorService; @RestController
@RequestMapping("/author")
public class AuthorController { @Autowired
private AuthorService authorService; /**
* 查询用户列表
*/ @GetMapping("/getAuthorList")
public Map<String, Object> getAuthorList(HttpServletRequest request) { List<Author> authorList = this.authorService.findAuthorList();
Map<String, Object> param = new HashMap<String, Object>();
param.put("total", authorList.size());
param.put("rows", authorList);
return param;
} /**
* 查询用户信息
*/
//@RequestMapping(value = "/getAuthor",method = RequestMethod.GET)
@GetMapping("/getAuthor")
public Author getAuthor() {
Author author = this.authorService.findAuthor(1L);
if (author == null) {
throw new RuntimeException("查询错误");
}
return author;
} /**
* 新增方法
*/
@RequestMapping(value ="/add",method = RequestMethod.GET)
public void add() {
String realName = "";
String nickName = "";
try {
this.authorService.add(realName, nickName);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("新增错误");
}
} /**
* 更新方法
*/
@RequestMapping(value ="/update")
public void update() {
try {
this.authorService.update("cyj", "", 1L);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("更新错误");
}
}
/**
* 删除方法
*/
@RequestMapping(value ="/delete")
public void delete() {
try {
this.authorService.delete(1L);
} catch (Exception e) {
throw new RuntimeException("删除错误");
}
}
}
方案二 通过配置文件的方式
实体对象
package com.boot.mybatis.entity;
import com.alibaba.fastjson.annotation.JSONField;
public class Author {
private Long id;
@JSONField(name="real_name")
private String realName;
@JSONField(name="nick_name")
private String nickName;
// SET和GET方法
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
}
配置相关
在 src/main/resources/mybatis/AuthorMapper.xml 中配置数据源信息。
<?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.boot.mybatis.dao.AuthorMapper2"> <!-- type为实体类Student,包名已经配置,可以直接写类名 -->
<resultMap id="authorMap" type="Author">
<id property="id" column="id" />
<result property="realName" column="real_name" />
<result property="nickName" column="nick_name" />
</resultMap> <select id="findAuthor" resultMap="authorMap" resultType="Author">
select id, real_name, nick_name from t_author where id = #{id}
</select>
</mapper>
在 src/main/resources/application.properties 中配置数据源信息。
#mybatis
mybatis.mapper-locations=classpath*:mybatis/*Mapper.xml
mybatis.type-aliases-package=com.boot.mybatis.entity
DAO相关
package com.boot.mybatis.dao;
import org.apache.ibatis.annotations.Param;
import com.boot.mybatis.entity.Author;
public interface AuthorMapper2 {
Author findAuthor(@Param("id") Long id);
}
Service相关
package com.boot.mybatis.service; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import com.boot.mybatis.dao.AuthorMapper2;
import com.boot.mybatis.entity.Author; @Service
public class AuthorService2 { @Autowired
private AuthorMapper2 authorMapper; public Author findAuthor(Long id) {
return this.authorMapper.findAuthor(id);
} }
Controller相关
package com.boot.mybatis.controller; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; import com.boot.mybatis.entity.Author;
import com.boot.mybatis.service.AuthorService2; @RestController
@RequestMapping(value=" Author2") public class AuthorController2 { @Autowired
private AuthorService2 authorService; /**
* 查询用户信息
*/
@RequestMapping(value = "/getuserId", method = RequestMethod.GET)
public Author getAuthor() {
Author author = this.authorService.findAuthor(2l);
if (author == null) {
throw new RuntimeException("查询错误");
}
return author;
} }
总结
上面这个简单的案例,让我们看到了 Spring Boot 整合 MyBatis 框架的大概流程。那么,复杂的场景,大家可以参考使用一些比较成熟的插件,例如com.github.pagehelper、mybatis-generator-maven-plugin等。
Spring boot之MyBatis的更多相关文章
- Spring Boot 整合 Mybatis 实现 Druid 多数据源详解
摘要: 原创出处:www.bysocket.com 泥瓦匠BYSocket 希望转载,保留摘要,谢谢! “清醒时做事,糊涂时跑步,大怒时睡觉,独处时思考” 本文提纲一.多数据源的应用场景二.运行 sp ...
- 使用intelliJ创建 spring boot + gradle + mybatis站点
Spring boot作为快速入门是不错的选择,现在似乎没有看到大家写过spring boot + gradle + mybatis在intellij下的入门文章,碰巧.Net同事问到,我想我也可以写 ...
- Spring Boot整合Mybatis并完成CRUD操作
MyBatis 是一款优秀的持久层框架,被各大互联网公司使用,本文使用Spring Boot整合Mybatis,并完成CRUD操作. 为什么要使用Mybatis?我们需要掌握Mybatis吗? 说的官 ...
- Spring boot整合Mybatis
时隔两个月的再来写博客的感觉怎么样呢,只能用“棒”来形容了.闲话少说,直接入正题,之前的博客中有说过,将spring与mybatis整个后开发会更爽,基于现在springboot已经成为整个业界开发主 ...
- Spring boot教程mybatis访问MySQL的尝试
Windows 10家庭中文版,Eclipse,Java 1.8,spring boot 2.1.0,mybatis-spring-boot-starter 1.3.2,com.github.page ...
- spring boot 实现mybatis拦截器
spring boot 实现mybatis拦截器 项目是个报表系统,服务端是简单的Java web架构,直接在请求参数里面加了个query id参数,就是mybatis mapper的query id ...
- spring boot 整合 mybatis 以及原理
同上一篇文章一样,spring boot 整合 mybatis过程中没有看见SqlSessionFactory,sqlsession(sqlsessionTemplate),就连在spring框架整合 ...
- Spring Boot集成MyBatis开发Web项目
1.Maven构建Spring Boot 创建Maven Web工程,引入spring-boot-starter-parent依赖 <project xmlns="http://mav ...
- 详解Spring Boot集成MyBatis的开发流程
MyBatis是支持定制化SQL.存储过程以及高级映射的优秀的持久层框架,避免了几乎所有的JDBC代码和手动设置参数以及获取结果集. spring Boot是能支持快速创建Spring应用的Java框 ...
- Spring Boot 整合MyBatis(1)
这篇文章介绍如何在Spring boot中整合Mybatis,其中sql语句采用注解的方式插入.后续文章将会介绍,如何使用xml方式. SSM SSH框架已经满足轻量级这个需求了,但是对于开发人员而言 ...
随机推荐
- springboot2.X版本得@Transactional注解事务不回滚不起作用
参考文章 https://my.oschina.net/happyBKs/blog/1624482 https://blog.csdn.net/u011410529/article/detail ...
- Javassist操作方法总结
CSDN参考Javassist tutorial 1.读取和输出字节码 ClassPool pool = ClassPool.getDefault(); //会从classpath中查询该类 CtCl ...
- 第二章 单表查询 T-SQL语言基础(2)
单表查询(2) 2.2 谓词和运算符 T-SQL有几种不同的语言元素可以指定逻辑表达式,例如,查询过滤器(WHERE和HAVING),CHECK约束,等等. 在逻辑表达式中可以使用各种谓词(取值为TR ...
- bash脚本测试总结
bash脚本测试总结 跟踪脚本的执行 可以让bash打印出你脚本执行的过程中的所有语句.这很简单,只需要使用bash的-x选项就可以做到,下面让我们来看一下. 下面的这段脚本,先是输出一个问候 ...
- leetcode 对角线遍历 JavaScript
JavaScript /** * @param {number[][]} matrix * @return {number[]} */ var findDiagonalOrder = function ...
- echarts图表自适应盒子的大小(盒子的大小是动态改变的),大到需要全屏展示
项目中用到了echarts,并且页面是自适应的,且页面中有一个[放大.缩小]功能,因此图表还需要根据盒子的大小来变化. 即:两个需求,如下: ① 图表根据窗口的大小自适应 ② 图表根据所在盒子的大小自 ...
- IT经理工作职责
IT经理工作职责: 1. 管理公司信息技术以及计算机系统. 2. 确保公司信息技术是可访问的并且配备了现有的可用的硬件和软件. 3. 监控并且维护公司信息技术并确保能够得到最大化的使用 ...
- 免费数学神器Mathpix发布移动版了,一起来写更快的公式
目录 1. 按 2. 下载地址 3. 介绍和使用 3.1. 介绍 3.2. 实际使用体验 1. 按 本文介绍的Mathpix可用于将手写的公式通过拍照或截图转成LaTeX 表达式. 写博客.记笔记最麻 ...
- SecureCRT 连接 Centos7.0 (NAT模式),且能连接公网。
1.打开物理主机运行-输入cmd,输入ipconfig,获取物理主机ip地址. ip:192.168.11.138 2.点击网络适配器,选择NAT模式. 3.点击Centos界面左上角-编辑-虚拟网络 ...
- HAproxy企业应用,TCP/HTTP动静分离
HAProxy的是一个免费的.开源的的tcp/http反向代理工具.负载均衡器,是一个企业非常快速和可靠的安全的解决方案,提供高可用性.高并发性,负载均衡和代理对TCP和基于HTTP的应用程序.它特别 ...