首页 > 其他分享 >Mybatis 入门实战(3)--Spring Boot 中使用 Mybatis

Mybatis 入门实战(3)--Spring Boot 中使用 Mybatis

时间:2022-11-27 11:11:08浏览次数:33  
标签:name -- Spring student org Mybatis import Student id

本文主要介绍如何在 Spring Boot 中使用 Mybatis,相关的环境及软件信息如下:Spring Boot 2.6.12、Mybatis 3.5.9。

1、工程整体结构

使用 Maven 来构建工程,工程目录结构如下:

2、pom.xml

关键配置如下:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.6.12</version>
    <relativePath />
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--Mybatis-->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.2.2</version>
    </dependency>
    <!--分页-->
    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper-spring-boot-starter</artifactId>
        <version>1.4.5</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.24</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
        </resource>
    </resources>
</build>

3、配置

3.1、应用配置(application.yml)

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://10.49.196.23:3306/test?useUnicode=true&characterEncoding=UTF-8
    username: root
    password: 123456

mybatis:
  configuration:
    map-underscore-to-camel-case: true

pagehelper:
  reasonable: true

3.2、日志配置(logback.xml)

<?xml version="1.0" encoding="utf-8"?>
<configuration debug="false">
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
          <level>INFO</level>
        </filter>
        
        <encoder>
            <pattern>%d %-5level [%thread] %logger[%L] -> %m%n</pattern>
        </encoder>
    </appender>

    <root level="info">
        <appender-ref ref="STDOUT" />
    </root>

    <logger name="com.abc.mapper" level="debug">
    </logger>

</configuration>

4、创建实体类

package com.abc.entity;

import lombok.Data;
import lombok.ToString;

import java.time.LocalDateTime;

@ToString
@Data
public class Student {
    private Long id;

    private LocalDateTime createTime;

    private LocalDateTime modifyTime;

    private String name;

    private Integer age;

    private String homeAddress;
}

5、创建 Mapper

package com.abc.mapper;

import com.abc.entity.Student;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

import java.util.List;
import java.util.Map;

@Mapper
public interface StudentMapper {
    void insert(Student student);

    void update(Student student);

    Student selectById(Long id);

    List<Student> select(@Param("name") String name, @Param("homeAddress") String homeAddress);

    List<Map<String, Object>> select2(String name, String homeAddress);

    void delete(Long[] ids);
}

StudentMapper 使用 XML 来编写 SQL,对应 XML 文件(StudentMapper.xml)内容为:

<?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.abc.mapper.StudentMapper">
    <insert id="insert" parameterType="com.abc.entity.Student" useGeneratedKeys="true" keyProperty="id">
        insert into a_student(create_time,modify_time,name,age,home_address)
        values(#{createTime},#{modifyTime},#{name},#{age},#{homeAddress})
    </insert>

    <update id="update" parameterType="com.abc.entity.Student">
        update a_student set id=id
        <if test="name != null and name != ''">
            ,name=#{name}
        </if>
        <if test="age != null">
            ,age=#{age}
        </if>
        <if test="homeAddress != null and homeAddress != ''">
            ,home_address=#{homeAddress}
        </if>
        where id=#{id}
    </update>

    <select id="selectById" resultType="com.abc.entity.Student">
        select * from a_student where id=#{id}
    </select>

    <select id="select" resultType="com.abc.entity.Student">
        select * from a_student where 1=1
        <if test="name != null and name != ''">
            and name like #{name}
        </if>
        <if test="homeAddress != null and homeAddress != ''">
            and home_address like #{homeAddress}
        </if>
    </select>

    <select id="select2" resultType="map">
        select * from a_student where 1=1
        <if test="param1 != null and param1 != ''">
            and name like #{param1}
        </if>
        <if test="param2 != null and param2 != ''">
            and home_address like #{param2}
        </if>
    </select>

    <delete id="delete">
        delete from a_student where id in
        <foreach collection="array" item="id" index="index" open="(" close=")" separator=",">
            #{id}
        </foreach>
    </delete>
</mapper>

表 a_student 的字段与实体类的属性一一对应(表中字段使用下划线写法,实体类属性使用驼峰写法),字段 id 为自增字段。

6、测试用例

package com.abc.service;

import com.abc.entity.Student;
import com.abc.mapper.StudentMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@RunWith(SpringRunner.class)
@SpringBootTest
public class StudentMapperCase {
    private static final Logger logger = LoggerFactory.getLogger(StudentMapperCase.class);

    @Autowired
    private StudentMapper studentMapper;

    @Test
    public void insert() {
        Student student = new Student();
        student.setCreateTime(LocalDateTime.now());
        student.setName("李白");
        student.setAge(30);
        student.setHomeAddress("长安");
        studentMapper.insert(student);
        logger.info("id={}", student.getId());
    }

    @Test
    public void update() {
        Student student = new Student();
        student.setId(261L);
        student.setName("李白2");
        studentMapper.update(student);
    }

    @Test
    public void selectById() {
        Student student = studentMapper.selectById(261L);
        logger.info(student.toString());
    }

    @Test
    public void select() {
        List<Student> students = studentMapper.select("%李%", "%长%");
        logger.info(students.toString());
    }

    @Test
    public void selectForPage() {
        PageHelper.startPage(10, 3);
        List<Student> students = studentMapper.select("%李%", "");
        PageInfo<Student> pageInfo = new PageInfo(students);
        logger.info(pageInfo.toString());
    }

    @Test
    public void select2() {
        List<Map<String, Object>> list = studentMapper.select2("%李%", "%长%");
        logger.info(list.toString());
    }

    @Test
    public void delete() {
        studentMapper.delete(new Long[]{260L, 263L});
    }
}

 

标签:name,--,Spring,student,org,Mybatis,import,Student,id
From: https://www.cnblogs.com/wuyongyin/p/16798334.html

相关文章

  • pyenv 的安装和使用 记录一下避免自己下次用时忘了
    1.安装和删除和更新(参考 ​​https://github.com/pyenv/pyenv-installer​​ )Install:$curlhttps://pyenv.run|bashpyenv.runredirectstotheinstallscriptinth......
  • win7+Python3.7+Cython +pyinstaller 打包方法
    1.Cython安装(将py编译成pyd,避免反编译)、pyinstaller安装pipinstall cythonpipinstallpyinstaller 2.cython使用建立编译脚本#!/usr/bin/python#-*-coding:utf-......
  • JMeter-正则表达式提取器的轻简教程
    1、取注册接口的用户名,赋值给变量username​2、将取到的username值给登录接口​3、验证登录是否成功​......
  • Python 爬虫:爬《权力的游戏》中英对照版
    VOA英文网有中英对照版 《权力的游戏》 ​​http://www.tingvoa.com/html/454618.html​​,但是只能在线看,而且每次不小段的太不方便了,想把它爬下来整理成大篇的,放到kindle......
  • Windows netstat 查看端口、进程占用
    目标:在Windows环境下,用netstat命令查看某个端口号是否占用,为哪个进程所占用.操作:操作分为两步:(1)查看该端口被那个PID所占用;方法一:有针对性的查看端口,使用命令Netstat–......
  • (一)KitJs瀑布流组件特点
    (一)KitJs瀑布流组件特点1.瀑布流形式呈现图片加载,鼠标滚动到底加载新的数据2.瀑布条数随窗口大小改变而改变,支持任意缩放窗口(二)使用方法core需要引用kit.js,IE下通过条件注......
  • 爬取百思不得姐上面的视频
    之前有了爬取糗事百科的经验,先想试着爬取一下视频,并下载到本地。爬取目标:爬取​​百思不得姐​​上面的视频把视频下载到本地敲一次回车就下载一个视频0、爬取效果1、确定......
  • 接口的扩展。
    今天给大家介绍一些有关扩展方法的一些知识,主要讲解一下在C#3.0中使用扩展方法来扩展接口。1、扩展方法跟原来类的方法重名时候的处理逻辑2、扩展方法的嵌套现......
  • readonly和const比较
    readonly和const比较前天犯了个低级错误,是关于readonly的,总结了一下:C#的readonly关键字只能在字段上面使用publicreadonlyTcpClientclient;不能在类,方法,属性上......
  • 事件是不是委托
    事件是不是委托首先给你解释一下委托是什么委托是一个类,这个类保存了一个对象和这个对象的一个方法,所以当你调用这个委托的时候就是调用保存的对象的哪个方法,委托的意......