SpringBoot使用Mybatis 快速入门

先说一下常用数据库连接库, 对比一下子

  • 原始java访问数据库,开发流程麻烦, 需要如下步骤
1、JDBC 注册驱动/加载驱动
    Class.forName("com.mysql.jdbc.Driver")
2、建立连接
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname","root","root");
3、创建Statement
    
4、执行SQL语句
    
5、处理结果集
    
6、关闭连接,释放资源

2、apache dbutils框架

JDBC要简单点, 对JDBC的一个封装。官网:https://commons.apache.org/proper/commons-dbutils/

3、jpa框架

spring-data-jpa 也是做【对象-关系表】之间的映射关系的,并将实体对象持久化到数据库中。
jpa在复杂查询的时候性能不是很好

4、Hiberante   解释:ORM:对象关系映射Object Relational Mapping

企业大都喜欢使用hibernate, 例如做一些内部OA系统, 快捷方便, 不需要特别灵活的业务可以使用

5、Mybatis框架

互联网行业通常使用mybatis,不提供对象和关系模型的直接映射,半ORM, 灵活度很高

接入Mybatis 连接mysql 增加数据获取增加后的数据id

  • 在启动类 xxxApplication.java里面添加扫描注解
@MapperScan("com.example.demo.mapper") // 包名 + dao层目录名称 我这是mapper

  • 增加依赖项 pom.xml
<!--        mybatis-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.1</version>
</dependency>
<!--mysql 连接-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.17</version>
</dependency>

<!-- 引入第三方数据源 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.6</version>
</dependency>
  • 配置数据库连接 application.properties
#mybatis.type-aliases-package=net.xdclass.base_project.domain
#可以自动识别
spring.datasource.driver-class-name =com.mysql.cj.jdbc.Driver
useUnicode=true&characterEncoding=utf-8
spring.datasource.url=jdbc:mysql://localhost:3306/u_test?useUnicode=true&characterEncoding=utf-8
spring.datasource.username =root
spring.datasource.password =123456
#如果不使用默认的数据源 (com.zaxxer.hikari.HikariDataSource)
#spring.datasource.type =com.alibaba.druid.pool.DruidDataSource
spring.datasource.type =com.alibaba.druid.pool.DruidDataSource
# sql输出
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl 

加载配置,注入到sqlSessionFactory等都是springBoot帮我们完成

  • 编写mapper 也就是dao  UserMapper.java
package com.example.demo.mapper;

import com.example.demo.bean.UserBean;
import org.apache.ibatis.annotations.*;

import java.util.List;

//@Mapper 因为直接在入口文件做扫描了 所以不需要写
public interface UserMapper {
    @Insert("insert into users(name, bio) values(#{name}, #{bio})")
    @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id") // keyProperty java对象的属性 keyColumn 数据库的键
    int insert(UserBean user);

}
  • 编写逻辑层 Service.
  1. UserService (interface)
package com.example.demo.service;

import com.example.demo.bean.UserBean;

/**
 * 用户业务逻辑
 */
public interface UserService {
    public int add(UserBean user);
}
  1. impl/UserServiceImpl 编写UserService的实现
package com.example.demo.service.impl;

import com.example.demo.bean.UserBean;
import com.example.demo.controller.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service // 标注是Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public int add(UserBean user) {
        userMapper.insert(user);
        return user.getId();
    }
}
  • 编写控制器 UserController.java
package com.example.demo.controller;

import com.example.demo.bean.UserBean;
import com.example.demo.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
public class UserController {

    @Autowired
    private UserService userService;


    @GetMapping("/api3/v1/add")
    public int add()
    {
        UserBean user = new UserBean();
        user.setBio("这是一个新签名");
        user.setName("憧憬");
        return userService.add(user);
//        return 1;
    }
}
  • 效果
添加用户mybatis效果

您的支持是对我最大的鼓励!

发表于: 作者:憧憬。
关注互联网以及分享全栈工作经验的原创个人博客和技术博客,热爱编程,极客精神
Github 新浪微博 SegmentFault 掘金专栏