springboot简易整合mybatis

2023-05-16

SpringBoot整合Mybatis篇


实现单表mybatis整合

准备sql:


--创建数据库
create database if not exists `mybatis`;
--修改数据库默认字节编码
alter database `mybatis` character set utf8;
--使用数据库
use `mybatis`;
--创建表
create table if not exists `student`(
    `id` int(11) not null Auto_Increment comment '编号',
    `name` varchar(255) not null comment '姓名',
    `sex` varchar(255) not null comment '性别',
    primary key(`id`)
)engine=InnoDB default charset =utf8;  

目录结构:

 

mybatis、mysql驱动、lombok依赖


        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--lombok 在springboot仓库中版本号-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>  

yaml配置文件:


#mysql驱动就是连接数据库,mybatis就是映射
​
# 应用名称
spring:
  application:
    name: my  #自己SpringBootApplication
  datasource:
    # 数据库驱动:
    driver-class-name: com.mysql.cj.jdbc.Driver
    # 数据库驱动:
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&characterEncoding=utf-8
    # 数据库用户名&密码:
    username: root 
    password: 123456
    # 数据源名称
    name: defaultDataSource
mybatis:
  #下面这些内容是为了让MyBatis映射
  #指定Mybatis的Mapper文件
  mapper-locations: classpath*:/mappers/*.xml
  #指定Mybatis的实体目录,如同取别名
  type-aliases-package: com.my.entity  

entity实体类:


package com.my.entity;
​
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
​
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
    private Integer id;
    private String name;
    private String sex;
}  

@Mapper与@MapperScan的关系

mapper持久层:@Mapper对单个数据层接口注入到spring容器中


package com.my.mapper;
​
import com.my.entity.Student;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Delete;
​
import java.util.List;
​
@Mapper
public interface StudentMapper {
    List<Student> findAll();
    int insertTo(Student student);
    @Delete("delete from student where id=#{id}")
    int deleteStudent(Integer id);
}  

MyApplication主启动类:@MapperScan是对多个数据层接口的注入


package com.my;
​
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
​
@SpringBootApplication
@MapperScan(basePackages = "com.my.mapper")
public class MyApplication {
​
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
​
}  

studentMapper.xml文件,SQL


<?xml version="1.0" encoding="UTF8" ?>
<!--含有中文注释报错,删除utf-8中的”-“-->
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.my.mapper.StudentMapper">
​
<!--    数据库中的字段名与实体类中的属性名不一致:
            一使用as:
                select password as pwd form student
            二使用resultMap映射:
                <resultMap id="studentMap" type="student">
                    <result column="password" property="pwd"/>
                </resultMap>
-->
<!--  parameterType="com.my.entity.Student",使用别名就可以直接使用实体类小写  -->
    <insert id="insertTo" parameterType="student">
        insert into student(id,name,sex) value (#{id},#{name},#{sex});
    </insert>
    <select id="findAll" resultType="com.my.entity.Student">
        select * from student;
    </select>
</mapper>  

MyApplicationTest测试类:


package com.my;
​
import com.my.entity.Student;
import com.my.mapper.StudentMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
​
import java.util.List;
​
@SpringBootTest
public class MyApplicationTests {
​
    @Autowired
    private StudentMapper studentMapper;
​
    @Test
    public void findAllStudent() {
        List<Student> students=studentMapper.findAll();
        for (Student student:students) {
            System.out.println(student.toString());
        }
    }
​
    @Test
    public void insertStudent(){
        Student student=new Student(5,"nini","男");
        int a=studentMapper.insertTo(student);
        System.out.println(a);
    }
    
    @Test
    public void delStudent(){
        int b=studentMapper.deleteStudent(2);
        System.out.println(b);
    }
​
}  

实验自我体验

自我实验报错有:

一、.properties与.yaml配置文件中,mybatis.mapper-locations写法不一致,

.properties:


mybatis.mapper-locations=classpath:mappers/*.xml  

.yaml:


mybatis:
  mapper-locations: classpath*:/mappers/*.xml  

二、mapper.xml文件,接收接口传来的参数,在parameterType="全路径",不然就要在yaml或者properties文件中,定义包或者类别名,使其自动匹配,会按照小写等匹配


mybatis:
  #下面这些内容是为了让MyBatis映射
  #指定Mybatis的Mapper文件
  type-aliases-package: com.my.entity  

三、存入的文件有乱码,一优先考虑配置文件中,数据库连接配置characterEncoding=utf-8没,之后在考虑其他,如数据库是否是默认字节编码等等


spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&characterEncoding=utf-8  

四、对于简单的sql我们,可以直接在mapper接口的方法上直接写入,如同以下


@Delete("delete from student where id=#{id}")
int deleteStudent(Integer id);  

五、写代码一定要仔细,尽量避免不必要的麻烦!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

springboot简易整合mybatis 的相关文章

随机推荐

  • JAVA 实参和形参

    形参 xff1a 是指在定义函数 时使用的参数 xff0c 目的是用于接收调用该函数时传入的参数 简单理解 xff0c 就是所有函数 xff08 即方法 xff09 的参数都是形参 实参 xff1a 在调用有参函数时 xff0c 主调函数和
  • JAVA 包装类

    1 概念 Java是一个面向对象的编程语言 xff0c 但是Java中的八种基本数据类型却是不面向对象的 xff0c 为了使用方便和解决这个不足 xff0c 在设计类时为每个基本数据类型设计了一个对应的类进行代表 xff0c 这样八种基本数
  • swagger被拦截器拦截

    配置swagger文档 xff0c 被拦截器拦截不能使用 拦截器中添加以下配置 xff0c 适当修改即可使用 重写addInterceptors registry addInterceptor new UserInterceptor add
  • JAVA之JDBC连接数据库

    前景说明 xff1a 在我们刚开始使用数据库的时候 xff0c 发现只能在mysql编辑器里面使用sql语句来完成对数据库的操作 xff0c 那我们怎么来通过Java来操控数据库呢 xff1f 这个时候就有了JDBC的出现 1 什么是JDB
  • Css margin 和 float浮动

    1 浮动 定义 浮动是css里面布局最多的一个属性 xff0c 也是很重要的一个属性 float xff1a 表示浮动的意思 它有四个值 none 表示不浮动 xff0c 默认right xff1a 表示右浮动left 表示左浮动 floa
  • Java Servlet组件

    1 什么是Servlet xff1f 从广义上来讲 xff0c Servlet规范是Sun公司制定的一套技术标准 xff0c 包含与Web应用相关的一系列接口 xff0c 是Web应用实现方式的宏观解决方案 而具体的Servlet容器负责提
  • JAVA 之 Ajax

    1 什么是Ajax xff1f AJAX xff08 Asynchronous Javascript And XML xff09 翻译成中文就是 异步Javascript和XML 即是用Javascript语言与服务器进行异步交互 xff0
  • Servlet 的Request和Response

    1 Request和Response概述 1 Request 获取请求数据 浏览器会发送HTTP请求到后台服务器 Tomcat HTTP的请求中会包含很多请求数据 请求行 43 请求头 43 请求体 后台服务器 Tomcat 会对HTTP请
  • 链接标签的使用

    什么是链接 xff1f 链接相当于是一个传送门 xff0c 点击链接就可以从该页面 xff0c 跳转到其他页面 xff0c 或者从该页面跳转到该页面的其他地方 链接的表现形式有哪些 xff1f 链接可以 表现为文字 xff0c 图片 xff
  • 报错 java: 程序包org.apache.ibatis.annotations不存在

    今天在使用mybatis运行项目时 xff0c 项目忽然报错了 xff0c 检查了自己的pom xml文件也没有问题 xff0c 报错情况如图 xff1a 在网上找了一大堆方法 xff0c 都没有解决问题 xff0c 这里附上一个网上的常用
  • spring框架

    文章内容 介绍spring框架 为什么要使用spring框架 如何使用spring IOC控制反转 1 介绍spring框架 1 spring是一个轻量级开源的JAVAEE框架 2 Spring提高了IOC和AOP IOC 控制反转 把创建
  • Ubuntu忘记密码怎么办 如何重置Ubuntu登入密码

    1 首先重新启动Ubuntu系统 xff0c 然后快速按下shift键 xff0c 以调出grub启动菜单 2 在这里我们选择第二个 xff08 Ubuntu高级选项 xff09 xff0c 选中后按下Enter键 3 选择第二个recov
  • 快速掌握e语言,以js语言对比,快速了解掌握。

    易语言 xff0c 怎么调试输出 xff0c 查看内容 在js语言里 xff0c 弹窗是 alert 在易语言里 xff0c 弹窗是 信息框 弹出显示内容 0 标题 在js语言里 xff0c 调试输出是 console log 在易语言里
  • java 实现Comparable接口排序,升序、降序、倒叙

    本人由于项目开发中需要对查询结果list进行排序 xff0c 这里根据的是每一个对象中的创建时间降序排序 本人讲解不深 xff0c 只实现目的 xff0c 如需理解原理还需查阅更深的资料 1 实现的效果 2 创建排序的对象 package
  • gitbash不能粘贴

    点击鼠标滚轮或者shift 43 ins
  • Hive安装与配置常见问题解决

    欢 43 迎使用Markdown编辑器 提示 xff1a 文章写完后 xff0c 目录可以自动生成 xff0c 如何生成可参考右边的帮助文档 目录 前言一 Hive是什么 xff1f 二 安装步骤1 引入jar包2 配置步骤1 hive s
  • 【Linux】生产者消费者模型

    文章目录 1 生产者消费者模型1 1生产者消费者模型的特点1 2生产者消费者模型的原则1 3生产者消费者模型的优点 2 基于阻塞队列的生产者消费者模型2 1如何理解生产者消费者模型的并发 xff1f 3 信号量3 1信号量接口3 2基于环形
  • Ubuntu设置允许root用户登录

    Ubuntu激活root用户 sudo passwd root 设置root密码 设置允许root通过ssh默认登录 vim etc ssh sshd config root权限编辑 PermitRootLogin yes 在第一行添加内容
  • python编写程序统计一元人民币换成一分、两分和五分的所有兑换方案个数(用while循环)

    a 61 int input 34 输入钱数 xff08 单位 xff1a 元 xff09 34 e 61 a 100 count 61 0 i 61 1 while i lt e 5 43 1 i 43 61 1 b 61 e 5 i 2
  • springboot简易整合mybatis

    SpringBoot整合Mybatis篇 实现单表mybatis整合 准备sql 创建数据库 create database if not exists 96 mybatis 96 修改数据库默认字节编码 alter database 96