SpringBoot整合Mybatis

SpringBoot整合Myabtis

1.新建SpringBoot项目,勾选依赖

2.创建数据库(为了方便测试,数据库表相对简单)

DROP DATABASE IF EXISTS mybatis;
CREATE DATABASE mybatis;

DROP TABLE  IF EXISTS USER;
CREATE TABLE USER(
	id INT PRIMARY KEY AUTO_INCREMENT,
	username VARCHAR(32) NOT NULL COMMENT '姓名',
	PASSWORD VARCHAR(32) NOT NULL COMMENT '密码'
)ENGINE=INNODB AUTO_INCREMENT=1 CHARSET=utf8;

INSERT INTO USER(username,PASSWORD) VALUES("niubi","123456");
INSERT INTO USER(username,PASSWORD) VALUES("wocao","123456");
INSERT INTO USER(username,PASSWORD) VALUES("Java","123456");
INSERT INTO USER(username,PASSWORD) VALUES("python","123456");
INSERT INTO USER(username,PASSWORD) VALUES("C","123456");

3.创建实体类和对应的DAO接口

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private Integer id;
    private String username;
    private String password;
}
@Mapper//表示本类是一个Mybatis的mapper
@Repository//不加也可以,但是Controller会报错,但是不影响正常运行
public interface UserMapper {
    //获取所有用户
    List<User> findAllUser();
    //根据id获取用户
    User findUserById(@Param("id") int id);
    //增加一个用户
    int addUser(User user);
    //删除一个用户
    int deleteUser(@Param("id") int id);
}

4.创建UserMapper配置文件

<?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.gaoteng.mapper.UserMapper">
    
    <select id="findAllUser" resultType="User">
        select * from user
    </select>
</mapper>

5.编写application.properties配置文件

# 配置数据源
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&serverTimezone=UTC&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 开启别名映射
mybatis.type-aliases-package=com.gaoteng.pojo
# mapper的路径 就是xml配置文件中的<mappers>标签
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

6.编写Controller

@RestController
public class TestController {
    @Autowired
    UserMapper mapper;
    @GetMapping("findAll")
    public List<User> findAll(){
        List<User> userList = mapper.findAllUser();
        return userList;
    }
}

7.运行

数据可以获取到!!!

注意: 可以在application.yaml或者application.properties中设置Mybatis的一些设置,也可以自己编写mybatis-config.xml,然后在application.yaml或者application.properties中通过

mybatis.config-location=classpath:mybatis/mapper/mybatis-config.xml

来进行配置.

posted @ 2020-06-05 13:16  毕竟是曾经  阅读(165)  评论(0编辑  收藏  举报