Spring Boot入门教程2-1、使用Spring Boot+MyBatis访问数据库(CURD)注解版
一、前言
什么是MyBatis?
MyBatis是目前Java平台最为流行的ORM框架
https://baike.baidu.com/item/MyBatis/2824918本篇开发环境
1、操作系统: Windows 10 X64
2、Java SDK: jdk-8u141
3、Maven:3.5
4、IDE:IntelliJ IDEA 2017
5、Spring Boot:1.5.6
本项目构建基于:https://ken.io/note/springboot-course-basic-helloworld
二、Spring Boot整合MyBatis
- 引入核心依赖
| package | 说明 |
|---|---|
| mybatis-spring-boot-starter | MyBatis核心for Spring Boot |
| mysql-connector-java | 用于连接MySQL |
pom.xml文件:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
- 配置数据库连接
在配置文件:application.yml中增加以下配置:
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/course?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=utf-8
username: mysql
password: password
数据库自行创建MySQL下载地址:https://dev.mysql.com/downloads/
- Package创建
| Package | 说明 |
|---|---|
| io.ken.springboot.course.model | 用于存放实体 |
| io.ken.springboot.course.dao | 用于存放数据访问映射*mapper |
- user表&实体创建
1、user表创建脚本
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`hobby` varchar(500) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2、user实体
package io.ken.springboot.course.model;
public class User {
private int id;
private String name;
private int age;
private String hobby;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
}
getger和setter可以选中类名之后使用快捷键Alt+Insert生成
- 创建UserMapper,用于User数据库操作映射
package io.ken.springboot.course.dao;
import io.ken.springboot.course.model.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user WHERE id = #{id}")
User queryById(@Param("id") int id);
@Select("SELECT * FROM user")
List<User> queryAll();
@Insert({"INSERT INTO user(name,age,hobby) VALUES(#{name},#{age},#{hobby})"})
int add(User user);
@Delete("DELETE FROM user WHERE id = #{id}")
int delById(int id);
@Update("UPDATE user SET name=#{name},age=#{age},hobby=#{hobby} WHERE id = #{id}")
int updateById(User user);
}
- 创建UserController并提供API
package io.ken.springboot.course.controller;
import io.ken.springboot.course.dao.UserMapper;
import io.ken.springboot.course.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
UserMapper userMapper;
@RequestMapping("/querybyid")
@ResponseBody
User queryById(int id) {
return userMapper.queryById(id);
}
@RequestMapping("/queryall")
@ResponseBody
List<User> queryAll() {
return userMapper.queryAll();
}
@RequestMapping("/add")
@ResponseBody
String add(User user) {
return userMapper.add(user) == 1 ? "success" : "failed";
}
@RequestMapping("/updatebyid")
@ResponseBody
String updateById(User user) {
return userMapper.updateById(user) == 1 ? "success" : "failed";
}
@RequestMapping("/delbyid")
@ResponseBody
String delById(int id) {
return userMapper.delById(id) == 1 ? "success" : "failed";
}
}
- API测试
| API | 示例 |
|---|---|
| 添加用户 | /user/add?name=tom&age=1&hobby=football |
| 更新用户 | /user/updatebyid?name=ken&age=18&hobby=coding&id=1 |
| 查询指定用户 | /user/querybyid?id=1 |
| 查询所有用户 | /user/queryall |
| 删除指定用户 | /user/delbyid?id=2 |
本文代码示例:https://github.com/ken-io/springboot-course/tree/master/chapter-02-01
- 系列名称:Spring Boot入门教程
- 下一篇:Spring Boot入门教程2-2、使用Spring Boot+MyBatis访问数据库(CURD)xml配置版
- 本篇首次发布:2017-08-15
- 本篇原文链接:https://ken.io/note/springboot-course-basic-curd-annotation
Spring Boot入门教程2-1、使用Spring Boot+MyBatis访问数据库(CURD)注解版的更多相关文章
- Spring Boot入门教程1、使用Spring Boot构建第一个Web应用程序
一.前言 什么是Spring Boot?Spring Boot就是一个让你使用Spring构建应用时减少配置的一个框架.约定优于配置,一定程度上提高了开发效率.https://zhuanlan.zhi ...
- Spring Boot 入门教程
Spring Boot 入门教程,包含且不仅限于使用Spring Boot构建API.使用Thymeleaf模板引擎以及Freemarker模板引擎渲染视图.使用MyBatis操作数据库等等.本教程示 ...
- Java - Struts框架教程 Hibernate框架教程 Spring框架入门教程(新版) sping mvc spring boot spring cloud Mybatis
https://www.zhihu.com/question/21142149 http://how2j.cn/k/hibernate/hibernate-tutorial/31.html?tid=6 ...
- Spring Boot入门教程(1)
Spring Boot入门教程(1) 本文将使用Spring Boot一步步搭建一个简单的Web项目来帮助你快速上手. 将要用到的工具 JDK 8 IntelliJ IDEA(Ultimate Edi ...
- Spring Cloud 入门教程 - 搭建配置中心服务
简介 Spring Cloud 提供了一个部署微服务的平台,包括了微服务中常见的组件:配置中心服务, API网关,断路器,服务注册与发现,分布式追溯,OAuth2,消费者驱动合约等.我们不必先知道每个 ...
- Spring Cloud 入门教程(七): 熔断机制 -- 断路器
对断路器模式不太清楚的话,可以参看另一篇博文:断路器(Curcuit Breaker)模式,下面直接介绍Spring Cloud的断路器如何使用. SpringCloud Netflix实现了断路器库 ...
- Spring Cloud 入门教程(六): 用声明式REST客户端Feign调用远端HTTP服务
首先简单解释一下什么是声明式实现? 要做一件事, 需要知道三个要素,where, what, how.即在哪里( where)用什么办法(how)做什么(what).什么时候做(when)我们纳入ho ...
- Spring Cloud 入门教程(八): 断路器指标数据监控Hystrix Dashboard 和 Turbine
1. Hystrix Dashboard (断路器:hystrix 仪表盘) Hystrix一个很重要的功能是,可以通过HystrixCommand收集相关数据指标. Hystrix Dashboa ...
- Spring Cloud 入门教程(十):和RabbitMQ的整合 -- 消息总线Spring Cloud Netflix Bus
在本教程第三讲Spring Cloud 入门教程(三): 配置自动刷新中,通过POST方式向客户端发送/refresh请求, 可以让客户端获取到配置的最新变化.但试想一下, 在分布式系统中,如果存在很 ...
随机推荐
- 关于这个该死的报错:TypeError - 'undefined' is not a function (evaluating '_getTagName(currWindow).toLowerCase()')
在利用Selenium爬取页面信息的时候突然报错,第一条信息爬取的时候还好好的,第二条就不行了. 请参考网上的爬取代码: # coding=utf-8"""Created ...
- Coursera DeepLearning.ai Logistic Regression逻辑回归总结
既<Machine Learning>课程后,Andrew Ng又推出了新一系列的课程<DeepLearning.ai>,注册了一下可以试听7天.之后每个月要$49,想想还是有 ...
- JustMock .NET单元测试利器(一)
1.什么是Mock? Mock一词是指模仿或者效仿,用于创建实例和静态模拟.安排和验证行为.在软件开发中提及"mock",通常理解为模拟对象.模拟对象的概念就是我们想要创建一个可以 ...
- jsTree树形菜单分类
这里我演示的jsTree是基于ABP框架 ,展示部分代码,话不多说首先看效果如: 1:引入JS <link href="/jstree/themes/default/style.css ...
- 【Luogu1345】奶牛的电信(网络流)
[Luogu1345]奶牛的电信(网络流) 题面 题目描述 农夫约翰的奶牛们喜欢通过电邮保持联系,于是她们建立了一个奶牛电脑网络,以便互相交流.这些机器用如下的方式发送电邮:如果存在一个由c台电脑组成 ...
- Poj3321 Apple tree
翻译: 卡卡屋前有一株苹果树,每年秋天,树上长了许多苹果.卡卡很喜欢苹果.树上有N个节点,卡卡给他们编号1到N,根的编号永远是1.每个节点上最多结一个苹果.卡卡想要了解某一个子树上一共结了多少苹果. ...
- MySQL根据出生日期计算年龄的五种方法比较
方法一 SELECT DATE_FORMAT(FROM_DAYS(TO_DAYS(NOW())-TO_DAYS(birthday)), '%Y')+0 AS age 方法一,作者也说出了缺陷,就是当日 ...
- C++中不同变量、函数在内存中的内存情况《转》
一.一个C++编译的程序占用的内存分为以下几个部分 1.栈区:由编译器自动分配 存放函数的参数值,局部变量的值等,操作方式类似于数据结构中的栈. 2.堆区:一般由程序员分配释放,若程序员不释放,程序结 ...
- hive数据库的哪些函数操作是否走MR
平时我们用的HIVE 我们都知道 select * from table_name 不走MR 直接走HTTP hive 0.10.0为了执行效率考虑,简单的查询,就是只是select,不带count, ...
- 2D变形transform的translate和rotate
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...