0、前言

  mybatis属于半自动的ORM,相比hibernate这种全自动的ORM,兼顾了性能与易用;目前企业项目中,基本都是mybatis的天下;今天就来整合mybatis与MySQL;

1、整合

  1.-1、添加依赖:

        <!-- 集成mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>

1-2、创建数据表:

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(32) NOT NULL AUTO_INCREMENT COMMENT '用户ID',
`userName` varchar(32) NOT NULL COMMENT '用户名称',
`passWord` varchar(50) NOT NULL COMMENT '用户密码',
`realName` varchar(32) DEFAULT NULL COMMENT '中文名字',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; -- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('', 'anson', '', '张三');
INSERT INTO `user` VALUES ('', 'Alex', '', '李四');
INSERT INTO `user` VALUES ('', 'kks', '', '王五');

1-3、增加实体类User.java

package com.anson.model;

public class User {
private Integer id;
private String username;
private String password;
private String realname;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username == null ? null : username.trim();
}
public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
public String getRealname() {
return realname;
}
public void setRealname(String realname) {
this.realname = realname == null ? null : realname.trim();
}
}

1-4、增加Mapper接口UserMapper.java;注意添加@Repository注解

package com.anson.dao;

import com.anson.model.User;
import org.springframework.stereotype.Repository; @Repository //添加Repository注解
public interface UserMapper {
int deleteByPrimaryKey(Integer id); int insert(User record); int insertSelective(User record); User selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record);
}

1-5、添加Mapper对应的XML文件UserMapper.xml,注意<mapper namespace="com.anson.dao.UserMapper">对应Mapper包

<?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.anson.dao.UserMapper">
<resultMap id="BaseResultMap" type="com.anson.model.User">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="userName" jdbcType="VARCHAR" property="username" />
<result column="passWord" jdbcType="VARCHAR" property="password" />
<result column="realName" jdbcType="VARCHAR" property="realname" />
</resultMap>
<sql id="Base_Column_List">
id, userName, passWord, realName
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from user
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.anson.model.User">
insert into user (id, userName, passWord,
realName)
values (#{id,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
#{realname,jdbcType=VARCHAR})
</insert>
<insert id="insertSelective" parameterType="com.anson.model.User">
insert into user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="username != null">
userName,
</if>
<if test="password != null">
passWord,
</if>
<if test="realname != null">
realName,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=INTEGER},
</if>
<if test="username != null">
#{username,jdbcType=VARCHAR},
</if>
<if test="password != null">
#{password,jdbcType=VARCHAR},
</if>
<if test="realname != null">
#{realname,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.anson.model.User">
update user
<set>
<if test="username != null">
userName = #{username,jdbcType=VARCHAR},
</if>
<if test="password != null">
passWord = #{password,jdbcType=VARCHAR},
</if>
<if test="realname != null">
realName = #{realname,jdbcType=VARCHAR},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.anson.model.User">
update user
set userName = #{username,jdbcType=VARCHAR},
passWord = #{password,jdbcType=VARCHAR},
realName = #{realname,jdbcType=VARCHAR}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>

1-6、编写service接口UserService.java:

package com.anson.service;

import com.anson.model.User;

public interface UserService
{
int deleteByPrimaryKey(Integer id);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
}

编写接口实现类UserServiceImpl.java,注意增加@Service注解:

package com.anson.service.Impl;

        import com.anson.dao.UserMapper;
import com.anson.model.User;
import com.anson.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; /**
* @description: service实现类
* @author: anson
* @Date: 2019/9/5 0:37
* @version: 1.0
*/
@Service
public class UserServiceImpl implements UserService
{
@Autowired
UserMapper usermapper; @Override
public User selectByPrimaryKey(Integer id)
{
return usermapper.selectByPrimaryKey(id);
}
@Override
public int deleteByPrimaryKey(Integer id)
{
return usermapper.deleteByPrimaryKey(id);
}
@Override
public int insert(User record)
{
return usermapper.insert(record);
}
@Override
public int insertSelective(User record)
{
return usermapper.insertSelective(record);
}
@Override
public int updateByPrimaryKeySelective(User record)
{
return usermapper.updateByPrimaryKeySelective(record);
}
@Override
public int updateByPrimaryKey(User record)
{
return usermapper.updateByPrimaryKey(record);
} }

1-7、编写controller:

package com.anson.controller;

import com.anson.model.User;
import com.anson.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; /**
* @description: TODO
* @author: anson
* @Date: 2019/9/5 0:42
* @version: 1.0
*/ @RestController
@Api(value = "用户接口")
@RequestMapping("/user")
public class UserController
{
@Autowired
private UserService userservice; @ApiOperation(value = "获取用户", notes = "根据id查询用户信息")
@ApiImplicitParam(name = "id", value = "用户id", required=true, dataType="int") //API参数
@RequestMapping(value="/getUserById/{id}",method= RequestMethod.GET)
public User selectByPrimaryKey(@PathVariable int id)
{
return userservice.selectByPrimaryKey(id);
}
}

1-8、启动类中增加包扫描注解:

@SpringBootApplication
@MapperScan("com.anson.dao") //增加Mapper包扫描注解
public class application
{
public static void main(String[] args)
{
SpringApplication.run(application.class,args);
}
}

1-9、配置文件中增加数据源和mybatis的注解:

#服务器配置
server.port=8090 #mysql数据源配置
spring.datasource.driverClassName = com.mysql.cj.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
spring.datasource.username = root
spring.datasource.password =88888888 #mybatis配置
mybatis.type-aliases-package=com.anson.model
mybatis.mapperLocations=classpath:mapper/*Mapper.xml #showSql
logging.level.com.anson.dao=debug

好了,完毕,运行,可以在swagger中查看和运行接口:

可以看到已经正常运行了;

好了,本节到此为止,下节将讲介绍mybatis-generator自动生成实体、mapper和mapper对应的XML

源码地址:https://github.com/anson-yang/cloverDemo.git

小白的springboot之路(三)、集成mybatis与MySQL的更多相关文章

  1. 小白的springboot之路(一)、环境搭建、第一个实例

    小白的springboot之路(一).环境搭建.第一个实例 0- 前言 Spring boot + spring cloud + vue 的微服务架构技术栈,那简直是爽得不要不要的,怎么爽法,自行度娘 ...

  2. 小白的springboot之路(十五)、mybatis的PageHelper分页插件使用

    0.前言 用mybatis,那么分页必不可少,基本都是用PageHelper这个分页插件,好用方便: 1.实现 1.1.添加依赖: <!-- 3.集成 mybatis pagehelper--& ...

  3. SpringBoot 集成Mybatis 连接Mysql数据库

    记录SpringBoot 集成Mybatis 连接数据库 防止后面忘记 1.添加Mybatis和Mysql依赖 <dependency> <groupId>org.mybati ...

  4. SpringBoot 入门教程:集成mybatis,redis

    SrpingBoot相较于传统的项目具有配置简单,能快速进行开发的特点,花更少的时间在各类配置文件上,更多时间在具体业务逻辑上. SPringBoot采用纯注解方式进行配置,不喜欢xml配置的同学得仔 ...

  5. 小白的springboot之路(十六)、mybatis-plus 的使用

    0-前言 mybatis plus是对mybatis的增强,集成mybatis plus后,简单的CRUD和分页就不用写了,非常方便,五星推荐: 1-集成 1-1.添加依赖 <!-- .集成my ...

  6. Spring Boot(六)集成 MyBatis 操作 MySQL 8

    一.简介 1.1 MyBatis介绍 MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC代码和手动设置参数以及获取结果集. ...

  7. 小白的springboot之路(二)、集成swagger

    0-前言 现在的项目开发,基本都是前后端分离,后端专注于API接口开发,都需要编写和维护API接口文档.如果你还在用Word来编写接口文档,那你就out了,这个时候,当当当当~神兵利器swagger隆 ...

  8. 小白的springboot之路(五)、集成druid

    0-前言 Druid阿里巴巴开源的一个java数据库连接池,是Java语言中最好的数据库连接池,Druid能够提供强大的监控和扩展功能:集成它能够方便我们对数据库连接进行监控和分析,下面我们来集成它: ...

  9. 小白的springboot之路(十二)、集成log4j2日志

    0.前言 日志记录对系统来说必不可少,spring boot中常用的日志组件有log4j.logback.log4j2,其中logback是spring boot默认的,已自带:选用log4j2就可以 ...

随机推荐

  1. Python3爬虫(2)_利用urllib.urlopen发送数据获得反馈信息

    一.urlopen的url参数 Agent url不仅可以是一个字符串,例如:https://baike.baidu.com/.url也可以是一个Request对象,这就需要我们先定义一个Reques ...

  2. [考试反思]1014csp-s模拟测试73:侵蚀

    嗯...还是没有改变那个现状 依旧只是打满了暴力,虽说T2打的的确比暴力好很多,但是因为出题人没有设分所以和暴力等同. 离上面的分差还是大的很,下面还是追的很紧 而且进几场的排名也是连续下滑... 虽 ...

  3. spring session源码解析

    模块划分 core部分代码 存储实现部分部分: jdbc实现 具体存储的实现类 例如:org.springframework.session.jdbc.JdbcOperationsSessionRep ...

  4. 史上最详细的C语言和Python的插入排序算法

    史上最详细的C语言和Python的插入排序算法插入排序原理:所谓插入排序,就像我们在打牌(斗地主)时,整理我们自己手中自己的牌一样,就像是2,1,3,9,J,K,5,4,这四张牌.我们要把它其中的几张 ...

  5. getClass()和instanceof以及类的equals方法

    在比较两个类时,常见有两种做法,一种是x.getClass() == y; 一种是x instanceof y,下面我们来比较这两种做法的区别. getClass()返回一个对象所属的类 public ...

  6. jsp+servlet分页查询

    分页查询 减少服务器内存开销 提高用户体验 效果图 思绪图 分页显示Bean文件代码 package cn.ytmj.findlist.domain; import java.util.List; / ...

  7. PHP 性能优化 - php.ini 配置

    内存 默认设置 memory_limit = 128M 单个进程可使用的内存最大值,这个值的设定可以从以下几点考虑: 应用的类型.如果是内存集中型应用,可增加该值: 单个 PHP 进程平均消耗的内存, ...

  8. 2018年航空概论课后作业(PS:部分答案不正确, 综合得分:83.6)

    1 [单选题]航空是指载人或不载人的飞行器在地球____的航行活动. • A.高空• B.大气层内• C.宇宙• D.大气层外我的答案:B 得分: 33.3分 2 [多选题]军用飞机可分为____两大 ...

  9. nyoj 32-组合数(next_permutation, stack, set)

    32-组合数 内存限制:64MB 时间限制:3000ms Special Judge: No accepted:8 submit:11 题目描述: 找出从自然数1.2.... .n(0<n< ...

  10. django_3:url配置

    浏览器url访问——url.py中正则匹配——转向对应的视图处理方法——在view.py中找到方法执行——在方法中一般会用到render渲染到.html文件——再用到.html url使用方式: 正则 ...