SSM框架再熟悉不过了,不过以前通常是使用XML写SQL语句

这里用SpringBoot整合Mybatis并且使用注解进行开发

依赖:

        <!-- Mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- Druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.6</version>
</dependency>

配置:不需要指定驱动类,SpringBoot会自动扫描:com.mysql.cj.jdbc.Driver

spring.datasource.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=xuyiqing
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

user表:

CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(128) DEFAULT NULL,
`phone` varchar(16) DEFAULT NULL,
`create_time` datetime DEFAULT NULL,
`age` int(4) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

对应实体类:

package org.dreamtech.springboot.domain;

import java.util.Date;

public class User {
private int id;
private String name;
private String phone;
private int age;
private Date createTime; 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 String getPhone() {
return phone;
} public void setPhone(String phone) {
this.phone = phone;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public Date getCreateTime() {
return createTime;
} public void setCreateTime(Date createTime) {
this.createTime = createTime;
} @Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", phone=" + phone + ", age=" + age + ", createTime=" + createTime
+ "]";
}
}

添加用户的Demo做整合

Mapper:

package org.dreamtech.springboot.mapper;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.dreamtech.springboot.domain.User; public interface UserMapper {
@Insert("INSERT INTO user(name,phone,create_time,age) VALUES(#{name},#{phone},#{createTime},#{age})")
@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
int insert(User user);
}

Service:

package org.dreamtech.springboot.service;

import org.dreamtech.springboot.domain.User;

public interface UserService {
int add(User user);
}
package org.dreamtech.springboot.service.impl;

import org.dreamtech.springboot.domain.User;
import org.dreamtech.springboot.mapper.UserMapper;
import org.dreamtech.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; @Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper; @Override
public int add(User user) {
userMapper.insert(user);
int id = user.getId();
return id;
} }

Controller:

package org.dreamtech.springboot.controller;

import java.util.Date;

import org.dreamtech.springboot.domain.User;
import org.dreamtech.springboot.service.UserService;
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.RestController; @RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService; @GetMapping("/add")
private Object add() {
User user = new User();
user.setAge(18);
user.setCreateTime(new Date());
user.setName("admin");
user.setPhone("100000");
userService.add(user);
return user;
}
}

最后别忘了一个细节:在启动类加上Mapper扫描注解

package org.dreamtech.springboot;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
@MapperScan("org.dreamtech.springboot.mapper")
public class SpringbootApplication { public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
} }

启动后访问localhost:8080/user/add

测试成功!

继续完成增删改查

有时候,开发者希望能够在控制台打印SQL语句,需要加一行配置文件

mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

CRUD完整实现:

package org.dreamtech.springboot.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.dreamtech.springboot.domain.User; public interface UserMapper {
/**
* 插入对象
*
* @param user 对象
* @return int
*/
@Insert("INSERT INTO user(name,phone,create_time,age) VALUES(#{name},#{phone},#{createTime},#{age})")
@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
int insert(User user); /**
* 查找全部
*
* @return
*/
@Select("SELECT * FROM user")
@Results({ @Result(column = "create_time", property = "createTime", javaType = java.util.Date.class) })
List<User> getAll(); /**
* 根据ID找对象
*
* @param id ID
* @return
*/
@Select("SELECT * FROM user WHERE id=#{id}")
@Results({ @Result(column = "create_time", property = "createTime", javaType = java.util.Date.class) })
User findById(Long id); /**
* 更新对象
*
* @param user 对象
* @return
*/
@Update("UPDATE user SET name=#{name} WHERE id=#{id}")
int update(User user); /**
* 根据ID删除对象
*
* @param id ID
* @return
*/
@Delete("DELETE FROM user WHERE id=#{id}")
int delete(Long id);
}
package org.dreamtech.springboot.service;

import java.util.List;

import org.dreamtech.springboot.domain.User;

public interface UserService {
int add(User user); List<User> getAll(); User findById(Long id); int update(User user); int delete(Long id);
}
package org.dreamtech.springboot.service.impl;

import java.util.List;

import org.dreamtech.springboot.domain.User;
import org.dreamtech.springboot.mapper.UserMapper;
import org.dreamtech.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; @Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper; @Override
public int add(User user) {
userMapper.insert(user);
int id = user.getId();
return id;
} @Override
public List<User> getAll() {
return userMapper.getAll();
} @Override
public User findById(Long id) {
return userMapper.findById(id);
} @Override
public int update(User user) {
return userMapper.update(user);
} @Override
public int delete(Long id) {
return userMapper.delete(id);
} }
package org.dreamtech.springboot.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.dreamtech.springboot.domain.User;
import org.dreamtech.springboot.service.UserService;
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.RestController; @RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService; private Map<String, Object> modelMap = new HashMap<String, Object>(); @GetMapping("/add")
private Object add() {
User user = new User();
user.setAge(18);
user.setCreateTime(new Date());
user.setName("admin");
user.setPhone("100000");
userService.add(user);
return user;
} @GetMapping("/getall")
private Object getAll() {
modelMap.clear();
List<User> list = userService.getAll();
if (list.size() > 0) {
modelMap.put("users", list);
modelMap.put("success", true);
} else {
modelMap.put("success", false);
}
return modelMap;
} @GetMapping("/findbyid")
private Object findById(Long id) {
if (id == null || id < 0) {
modelMap.put("success", false);
}
modelMap.clear();
User user = userService.findById(id);
if (user != null) {
modelMap.put("success", true);
modelMap.put("user", user);
} else {
modelMap.put("success", false);
}
return modelMap;
} @GetMapping("/update")
private Object update() {
modelMap.clear();
User user = new User();
user.setId(1);
user.setName("newAmdin");
int effectedNum = userService.update(user);
if (effectedNum > 0) {
modelMap.put("success", true);
} else {
modelMap.put("success", false);
}
return modelMap;
} @GetMapping("/delete")
private Object delete(Long id) {
if (id == null || id < 0) {
modelMap.put("success", false);
}
modelMap.clear();
int effectedNum = userService.delete(id);
if (effectedNum > 0) {
modelMap.put("success", true);
} else {
modelMap.put("success", false);
}
return modelMap;
}
}

事务:

如果用到事务相关的内容,需要在Service层加入一个注解@Transactional

    @Transactional(propagation = Propagation.REQUIRED)

SpringBoot 2.x (9):整合Mybatis注解实战的更多相关文章

  1. SpringBoot数据访问之整合mybatis注解版

    SpringBoot数据访问之整合mybatis注解版 mybatis注解版: 贴心链接:Github 在网页下方,找到快速开始文档 上述链接方便读者查找. 通过快速开始文档,搭建环境: 创建数据库: ...

  2. springBoot 整合 mybatis 项目实战

    二.springBoot 整合 mybatis 项目实战   前言 上一篇文章开始了我们的springboot序篇,我们配置了mysql数据库,但是我们sql语句直接写在controller中并且使用 ...

  3. SpringBoot整合Mybatis注解版---update出现org.apache.ibatis.binding.BindingException: Parameter 'XXX' not found. Available parameters are [arg1, arg0, param1, param2]

    SpringBoot整合Mybatis注解版---update时出现的问题 问题描述: 1.sql建表语句 DROP TABLE IF EXISTS `department`; CREATE TABL ...

  4. springboot整合mybatis(注解)

    springboot整合mybatis(注解) 1.pom.xml: <?xml version="1.0" encoding="UTF-8"?> ...

  5. Springboot 2.0.4 整合Mybatis出现异常Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required

    在使用Springboot 2.0.4 整合Mybatis的时候出现异常Property 'sqlSessionFactory' or 'sqlSessionTemplate' are require ...

  6. 二、springBoot 整合 mybatis 项目实战

    前言 上一篇文章开始了我们的springboot序篇,我们配置了mysql数据库,但是我们sql语句直接写在controller中并且使用的是jdbcTemplate.项目中肯定不会这样使用,上篇文章 ...

  7. Spring Boot整合Mybatis(注解方式和XML方式)

    其实对我个人而言还是不够熟悉JPA.hibernate,所以觉得这两种框架使用起来好麻烦啊. 一直用的Mybatis作为持久层框架, JPA(Hibernate)主张所有的SQL都用Java代码生成, ...

  8. SpringBoot数据访问之整合Mybatis配置文件

    环境搭建以及前置知识回顾 SpringBoot中有两种start的形式: 官方:spring-boot-starter-* 第三方:*-spring-boot-starter Mybatis属于第三方 ...

  9. (入门SpringBoot)SpringBoot项目数据源以及整合mybatis(二)

    1.配置tomcat数据源: #   数据源基本配置spring.datasource.url=jdbc:mysql://localhost:3306/shoptest?useUnicode=true ...

随机推荐

  1. 谈谈嵌套for循环的理解

    谈谈嵌套for循环的理解     说for的嵌套,先说一下一个for循环的是怎么用的.      这次的目的是为了用for循环输出一个乘法口诀表,一下就是我的一步步理解.    一.   语法:   ...

  2. 记一次关于return的错误

     有时候瞎JB程序,调一天东改西改,都发现不了错:到最后弄出来发现就是那样一个SB错误,真不知道该笑还是该哭. 这个if语句中的return,如果加了那么判断了if语句成立后,下面就不再执行了.   ...

  3. bzoj 3992 [SDOI2015] 序列统计 —— NTT (循环卷积+快速幂)

    题目:https://www.lydsy.com/JudgeOnline/problem.php?id=3992 (学习NTT:https://riteme.github.io/blog/2016-8 ...

  4. HashMap为什么比数组查询快

    通常数组不直接保存值,而是通过保存值的list.然后对list中的“值”使用equals方法比较,这部分查询速度自然慢.但是如果有好的散列函数,数组的每个位置就只有较少的“值”.因此,不是查询所有的l ...

  5. CS231n 2016 通关 第三章-SVM 作业分析

    作业内容,完成作业便可熟悉如下内容: cell 1  设置绘图默认参数 # Run some setup code for this notebook. import random import nu ...

  6. <正则吃饺子> :关于Guava中 Joiner 和 Splitter 的简单使用

    在现在项目中经常看到 这两个类的使用,开始时候不明白具体是做的什么事情,就单独拿出来学习下了,参照了网上的博文,这里主要是简单的讲讲用法. 具体对这两个类,不做过多介绍,有个在线文档,需要的可以自己去 ...

  7. java 随机颜色

    用HSV模型来实现颜色的随机,然后转为RGB模型 色相(H)是色彩的基本属性,就是平常所说的颜色名称,如红色.黄色等. 饱和度(S)是指色彩的纯度,越高色彩越纯,低则逐渐变灰,取0-100%的数值. ...

  8. 13.详解oauth2授权码流程

    13.详解oauth2授权码流程 把登陆系统单独独立出来,可以给自己写的微服务用,也可以给第三方的系统调用我们的服务 显式的和隐式的,两种方式,

  9. PHP中正则表达式学习及应用(二)

    正则表达式中的“元字符” * 匹配前一个内容的0次1次或多次 例如: <?php $mode="/go*gle/"; //前一个内容指的是 * 的前一个字符 o ,在$str ...

  10. 原创|高逼格企业级MySQL数据库备份方案,原来是这样....

    很多人,这里说的是运维工程师们,一提到写某某方案,很是头疼.不是上某度一统搜索,就是同样一句话在N个群全部群发一遍:“有没有某某方案,可以共享一下的吗??求助,各位大佬们”,估计十有八九,全部石沉大海 ...