spring boot 系列之七:SpringBoot整合Mybatis

springboot已经很流行,但是它仍需要搭配一款ORM框架来实现数据的CRUD,之前已经分享过JdbcTempleteJPA的整合,本次分享下Mybatis的整合。
对于mybatis的使用,需要创建mapper类和mapper.xml文件,这种创建比较烦,并且基本都是模板样式的,可以通过之前分享的《IDEA中mybatis generator使用》来自动创建完整的文件。由于本次deom中只有一个查询方法,就直接手写了,不再使用该插件了。
代码整体结构:

1.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.5.4</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.sam</groupId>
	<artifactId>springboot</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>springboot</name>
	<description>Demo project for Spring Boot</description>


	<properties>
		<java.version>1.8</java.version>
	</properties>
    
	<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.0</version>
		</dependency>

        <!--mysql db连接-->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>

        <!--连接池-->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.1.14</version>
		</dependency>

        <!--热部署-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

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

</project>

2.application.propertis

# jdbc配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mydb?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456

# 连接池
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

#mybatis的package别名
#mybatis.type-aliases-package=com.sam.springboot.pojo

#指定mybatis映射文件的路径
mybatis.mapper-locations=classpath:com/sam/springboot/mapper/*.xml

3.启动器

@SpringBootApplication
@MapperScan("com.sam.springboot.mapper") //扫描该包下的mapper文件
public class SpringbootApplication {

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

}

4.db脚本

CREATE TABLE `users`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NULL DEFAULT NULL,
  `age` int(11) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
);

-- ----------------------------
-- Records of users
-- ----------------------------
INSERT INTO `users` VALUES (1, 'sam', 32);
INSERT INTO `users` VALUES (2, 'hah ', 10);

5.pojo类

package com.sam.springboot.pojo;

/**
 * @description:
 * @author JAVA开发老菜鸟
 * @date: 2021-09-05 19:31
 */
public class User {
    private Integer id;

    private String name;

    private Integer age;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

6.mapper文件和mapper.xml

/**
 * @description:
 * @author: JAVA开发老菜鸟
 * @date: 2021-09-05 19:34
 */
public interface UserMapper {

    public List<User> getUserList(User user);
}
<?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.sam.springboot.mapper.UserMapper">
    <select id="getUserList" resultType="com.sam.springboot.pojo.User">
        select * from users
    </select>
</mapper>

7.service接口和实现

public interface UserService {

    List<User> getUserList(User user);
}
/**
 * @description:
 * @author: JAVA开发老菜鸟
 * @date: 2021-09-05 19:39
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public List<User> getUserList(User user) {
        return userMapper.getUserList(user);
    }
}

8.controller

@RestController
public class UserController {

    @Autowired
    UserService userService;

    @GetMapping("/getUserList.do")
    public void getUser() {
        List<User> list = userService.getUserList(new User());
        for (User user :list ){
            System.out.println(user.toString());
        }
    }
}

9.调试

浏览器访问http://localhost:8080/getUserList.do后查看控制台

posted @ 2021-09-05 20:51  JAVA开发老菜鸟  阅读(2746)  评论(0编辑  收藏  举报