SpringCloud 大型系列课程正在制造中,欢迎大家重视与提意见。 程序员每天的CV 与 板砖,也要知其所以然,本系列课程能够帮助初学者学习 SpringBooot 项目开发 与 SpringCloud 微服务系列项目开发


SpringBoot项目创立【SpringBoot系列1】


引入依赖 Spring Boot对于MyBatis的支持需求引入mybatis-spring-boot-starter的pom文件。

搜索 mvnrepository

SpringBoot 集成 MyBatis 框架 【SpringBoot系列2】

<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>3.0.1</version>
</dependency>

以及mysql的依赖

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.32</version>
</dependency>

2 增加MyBatis装备

增加MyBatis装备类,装备相关扫描路径,包括DAO,Model,XML映射文件的扫描。

import javax.annotation.Resource;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
@Configuration
@MapperScan("com.biglead.demo.mapper")    // 扫描DAO
public class MybatisConfig {
    @Resource
    private DataSource dataSource;
    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setTypeAliasesPackage("com.biglead.demo.pojo");    // 扫描Model
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        //对应的mapper 
        sessionFactory.setMapperLocations(resolver.getResources("classpath*:**/sqlmap/*.xml"));    // 扫描映射文件
        return sessionFactory.getObject();
    }
}
  • com.biglead.demo.pojo 数据目标实体地点的包
  • classpath*:**/sqlmap/*.xml MyBatis 对应的 xml 地点的包
  • com.biglead.demo.mapper MyBatis 对应的 mapper 接口地点的包

SpringBoot 集成 MyBatis 框架 【SpringBoot系列2】

3 增加数据源装备

翻开 application.yml ,增加MySQL数据源衔接信息。

server:
  port: 8899
spring:
  mvc:
    pathmatch:
      matching-strategy : ant-path-matcher
  datasource:
    url: jdbc:mysql://mysql:3306/spring_boot?useUnicode=true&zeroDateTimeBehavior=convertToNull&autoReconnect=true&characterEncoding=utf-8&useSSL=false
    username: testadmin
    password: qwert.12345
    driver-class-name: com.mysql.jdbc.Driver

3 基本操作

3.1 创立表

CREATE TABLE `t_user` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `user_name` varchar(255) DEFAULT NULL,
      `user_age` varchar(255) DEFAULT NULL,
      `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创立时刻',
      PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COMMENT='用户表';

然后插入几条数据

INSERT INTO `spring_boot`.`t_user` (`id`, `user_name`, `user_age`, `create_time`) VALUES (1, '张三', '22', '2023-03-14 12:09:20');
INSERT INTO `spring_boot`.`t_user` (`id`, `user_name`, `user_age`, `create_time`) VALUES (2, '李四', '33', '2023-03-14 12:09:24');

3.2 Controller

import com.biglead.demo.common.R;
import com.biglead.demo.pojo.UserInfo;
import com.biglead.demo.service.UserService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
@RestController
@RequestMapping("user")
public class UserController {
    @Resource
    private UserService userService;
    @GetMapping(value="/list")
    public R hello() {
        List<UserInfo> userInfoList = userService.findList();
        return R.okData(userInfoList);
    }
}
  • @RestController是@ResponseBody和@Controller的组合注解。
  • @Controller 注解将 UserController 类声明成一个控制器
  • @ResponseBody注解的作用是将控制器的方法返回的目标通过恰当的转换器转换为指定的格式之后,写入到Response目标的body区,一般用来返回JSON数据或者是XML数据

3.3 Service

CustomConfigService.java

public interface UserService {
    List<UserInfo> findList();
}

UserServiceImpl .java

import com.biglead.demo.mapper.UserMapper;
import com.biglead.demo.pojo.UserInfo;
import com.biglead.demo.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<UserInfo> findList() {
        return userMapper.selectList();
    }
}

3.4 Mapper 资源

UserMapper.java

import java.util.List;
public interface UserMapper {
    List<UserInfo> selectList();
}

UserMapper.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.biglead.demo.mapper.UserMapper">
    <resultMap id="BaseResultMap" type="com.biglead.demo.pojo.UserInfo">
        <id column="user_id" jdbcType="BIGINT" property="userId"/>
        <result column="create_time" property="createTime"/>
        <result column="user_name" property="userName"/>
        <result column="user_age" property="userAge"/>
    </resultMap>
    <select id="selectList" resultMap="BaseResultMap">
        select id, user_name, user_age, create_time
        from t_user
    </select>
</mapper>
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
import java.time.LocalDateTime;
@Data
@ToString
public class UserInfo implements Serializable {
    private Long userId;
    private String userName ;
    private String userAge;
    private LocalDateTime createTime;
}

4 打包资源

<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
        <!-- 打包时复制MyBatis的映射文件 -->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/sqlmap/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>  
                <directory>src/main/resources</directory>  
                    <includes> 
                        <include>**/*.*</include>  
                    </includes> 
                    <filtering>true</filtering>  
            </resource> 
        </resources>
    </build>

然后运转项目

SpringBoot 集成 MyBatis 框架 【SpringBoot系列2】

在Postman 中拜访 http://localhost:8899/user/list

SpringBoot 集成 MyBatis 框架 【SpringBoot系列2】
在 swagger 中 http://localhost:8899/swagger-ui.html
SpringBoot 集成 MyBatis 框架 【SpringBoot系列2】
SpringBoot 集成 MyBatis 框架 【SpringBoot系列2】

项目源码在这里 :gitee.com/android.lon… 有兴趣能够重视一下公众号:biglead

本文正在参与「金石方案」