《穿越SpringBoot 》 第四章-SpringBoot 访问数据库 | 第2节- SpringBoot 整合MyBatis

SpringBoot 整合Mybatis

前题:

借助:IntelliJ IDEAMaven构建工具,以及基于SpringBoot 2.3.4
官人如需使用 Maven 请阅读教程:Maven 构建工具的下载与安装
官人如需使用 IDEA 请阅读教程:IntelliJ IDEA

更多干货:

请阅读:《穿越SpringBoot》系列文章
请参考:Java学习资料

背景:

MyBatis是一款优秀的持久层框架,它支持定制化 SQL存储过程以及高级映射,几乎避免了所有的 JDBC 代码和手动设置参数以及获取结果集,使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录.

使用

目录结构:

在这里插入图片描述

pom.xml 依赖:

在pom.xml中添加Mybatis的依赖包mybatis-spring-boot-starter,该包拥有自动装配的特点
但是涉及到myBatis启动器适应SpringBoot的版本问题:

在这里插入图片描述

<?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.3.4.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>jdbc</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>jdbc</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
<!--mybatis-->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.1.3</version>
		</dependency>
<!--jdbc-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
<!--web	-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
<!--mysql-->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.13</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

application.properties配置文件

#端口
server.port=9090
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql:///test?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8
#静态资源缓冲
spring.thymeleaf.cache=false

mybatis.mapper-locations=classpath:mappers/*.xml
mybatis.type-aliases-package=com.example.jdbc.domain
# 驼峰命名规范
mybatis.configuration.map-underscore-to-camel-case=true

编写controller

package com.example.jdbc.controller;

import com.example.jdbc.domain.User;
import com.example.jdbc.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;
import java.util.List
@Controller
public class DemoController {
    
    
    @Resource
    private UserService userService;
    @GetMapping("/demo1")
    public String demo1(Model model){
    
    
        List<User> all = userService.getAll();
        System.out.println(all);
        model.addAttribute("user",all);
        return "index";
    }
}

编写service

package com.example.jdbc.service;
import com.example.jdbc.domain.User;
import java.util.List;
public interface UserService {
    
        
    List<User> getAll();
}
package com.example.jdbc.service.impl;

import com.example.jdbc.dao.UserDao;
import com.example.jdbc.domain.User;
import com.example.jdbc.mapper.UserMapper;
import com.example.jdbc.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    
    
    @Resource
    private UserMapper userMapper;

    @Override
    public List<User> getAll(){
    
    
        List<User> all = userMapper.getAll();
        return all;
    }
}

演示两种方式:

编写mapper

第一种是基于mybatis3.x版本后提供的注解方式
package com.example.jdbc.mapper;

import com.example.jdbc.domain.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface UserMapper {
    
    

        @Select("SELECT * FROM user")
        List<User> getAll();
        
        int insert(User user);
}

编写mapper.xml

第二种是早期写法,将SQL写在 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.jdbc.mapper.UserMapper">

    <insert id="insert" parameterType="com.example.jdbc.domain.User">
    INSERT INTO user(name,password,age) VALUES (#{name},#{password},#{age})
  </insert>

</mapper>

编写index页面

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<link rel="stylesheet" href="style.css">
<body>
<h1>测试SpringBoot 整合mybatis</h1>
    <ul>
        <li th:each="u : ${user}" th:object="${u}">
            <div>
                <span th:text="*{name}">水果</span>
                <span th:text="${u.age}">价格</span>
            </div>
        </li>
    </ul>
</body>
</html>

编写JdbcApplicationTests 测试类

package com.example.jdbc;

import com.example.jdbc.domain.User;
import com.example.jdbc.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
import java.sql.SQLException;

@RunWith(SpringRunner.class)
@SpringBootTest
class JdbcApplicationTests {
    
    

	@Resource
	private UserMapper userMapper;
	@Test
	void contextLoads() throws SQLException {
    
    
		User user = new User();
		user.setName("测试9");
		user.setPassword("123");
		user.setAge(25);
		int insert = userMapper.insert(user);
		System.out.println(insert);
	}
}

测试:

访问:http://localhost:9090/demo1

在这里插入图片描述
在这里插入图片描述

总结:

待完善…
本教程基于最新的spring-boot-starter-parent:2.3.4RELEASE编写,目前很多大佬都写过关于SpringBoot的教程了,如有雷同,请多多包涵.

猜你喜欢

转载自blog.csdn.net/weixin_47371330/article/details/109149190