0
点赞
收藏
分享

微信扫一扫

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

_阿瑶 2022-12-04 阅读 69

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

1、工程整体结构

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

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

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});
}
}

 



举报

相关推荐

0 条评论