SpringBoot整合Mybatis(XML版)

官网使用方法:http://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/zh/index.html

创建项目

SpringBoot整合Mybatis非常的方便,因为SpringBoot以及第三方为我们提供了很多start,整合某项技术,只需要简单的引入对应的start。我们使用Idea创建SpringBoot Initialize模块,勾选Mybatis依赖和MySQL的驱动依赖。
在这里插入图片描述
将配置文件改成yml格式,完成后项目结构如下:
在这里插入图片描述我们查看一下Pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.7.9-SNAPSHOT</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<groupId>com.rzg</groupId>
	<artifactId>springboot_03_mybatis</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.3.0</version>
		</dependency>

		<dependency>
			<groupId>com.mysql</groupId>
			<artifactId>mysql-connector-j</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>
</project>

pom文件中只有三个依赖:

  • mybatis-spring-boot-starter :整合mybatis的start,包含springboot基础的spring-boot-starter(不是spring-boot开头的start为第三方提供)
  • mysql-connector-j :mysql的驱动依赖
  • spring-boot-starter-test :springboot的测试依赖

写配置文件

在SpringBoot中的配置文件中设置数据库的配置信息

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatis
    username: root
    password: 123456

Mybatis会自动读自动探测存在的 DataSource

  • 将使用 SqlSessionFactoryBean 创建并注册一个 SqlSessionFactory 的实例,并将探测到的 DataSource 作为数据源
  • 将创建并注册一个从 SqlSessionFactory 中得到的 SqlSessionTemplate 的实例
  • 自动扫描你的 mapper,将它们与 SqlSessionTemplate 相关联,并将它们注册到Spring 的环境(context)中去,这样它们就可以被注入到你的 bean 中

如果使用的SpringBoot版本在2.4.3(不含)版本之前,使用Mysql8.0的版本需要设置时区,url设置为: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC(全球标准时间)或者serverTimezone=Asia/Shanghai

使用

创建dao接口

import com.rzg.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface UserDao {
    @Select("select * from user where id = #{id}")
    User getById(int id);
}

使用时:

@SpringBootTest
class Springboot02MybatisApplicationTests {

	@Autowired
	UserDao userDao;

	@Test
	void contextLoads() {
		User user = userDao.getById(5);
		System.out.println(user);
	}

}

测试输出:
User{id=5, name='王五', sex='女', age=23}

###########################################################################################################

创建SpringBoot项目并设置Pom文件

注意Mybatis的版本,高版本可能没有Maper注解

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.6</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>demo</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!-- MySQL连接 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--spring整合mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <resources>
        <!--将src中的xml properties yml 文件编译到 target文件夹中-->
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
                <include>**/*.yml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                    <include>**/*.yml</include>
                </includes>
                <filtering>false</filtering>
            </resource>

        </resources>

        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

创建项目结构

在这里插入图片描述

Controller

@RestController
public class MyController {

    @Autowired
    TypeMapper typeMapper;

    @RequestMapping("hello")
    public String hello (){
        List<Type> types = typeMapper.find();
        for (Type type : types){
            System.out.println(type);
        }
        return  "Hi";
    }
}

entity实体

package com.example.demo.entity;
public class Type {
    String type_id;
    String type_name;
	//省略Getter/Setter/toString

Mapper

@Mapper
@Repository
public interface TypeMapper {
    List<Type> find();

}

启动类


@SpringBootApplication

public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

Spring配置文件


server.port=8090

#?????
spring.datasource.username=******
spring.datasource.password= ******
spring.datasource.url= jdbc:mysql://***.***.***.***:3306/vem?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
spring.datasource.driver-class-name= com.mysql.cj.jdbc.Driver
spring.datasource.hikari.max-lifetime=120000 

mybatis.type-aliases-package= com.example.demo.entity

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.example.demo.mapper.TypeMapper">
    <select id="find" resultType="Type">
        select * from type
    </select>
</mapper>

数据库

在这里插入图片描述

编译后target的结构

在这里插入图片描述
测试请求:http://127.0.0.1:8090/hello
后台输出:
Type{type_id=‘1’, type_name=‘饮料’}
Type{type_id=‘2’, type_name=‘盒饭’}
Type{type_id=‘3’, type_name=‘零食’}
Type{type_id=‘4’, type_name=‘化妆品’}
Type{type_id=‘5’, type_name=‘日用品’}

注意:TypeMapper和XML一定要在一个文件夹下面。之前不注意,困扰了很久。
网上也有一些,吧XML配置文件放在Resoutces文件夹下面,然后配置路径,但是一定要注意编译后

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值