Spring Boot整合Mybatis

相信对很多Java程序员而言,SpringBoot是耳熟能详的一个框架了。在之前的时候,虽然使用过,但是记得不是很清楚,因此来回忆下它与Mybatis的使用。

第一步 创建数据库


新建一个用户表,并添加几个数据。

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `id` int(12) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `pwd` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 'tom', '123123');
INSERT INTO `user` VALUES (2, 'jerry', '123123');

SET FOREIGN_KEY_CHECKS = 1;

第二步 在application.properties文件中添加mybatis和数据库的配置信息

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/你的数据库名?serverTimezone=GMT%2B8
spring.datasource.username=用户名
spring.datasource.password=密码

#mybatis 映射文件
mybatis.mapper-locations=classpath:/mybatis/*.xml
#类型别名的配置文件
mybatis.type-aliases-package=com.example.mybatis01.entity
#开启驼峰式命名,不开启可能会导致部分数据为空
mybatis.configuration.map-underscore-to-camel-case=true
#设置日志等级
logging.level.com.example.mybatis01.mapper=debug

第三步 创建实体类对象

public class User {
    private Long id;
    private String userName;
    private String pwd;
    //省略set,get方法
}

第四步 添加mapper文件

@Mapper
@Repository
public interface UserMapper {
    public List<User> selectAll();

    public User getById(Long id);
}

第五步 创建服务层上的service接口

public interface UserService {
    public List<User> selectAll();

    public User getById(Long id);
}

第六步 添加service接口的继承类

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

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

    @Override
    public User getById(Long id) {
        return userMapper.getById(id);
    }
}

第七步 添加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.mybatis01.mapper.UserMapper">

    <select id="selectAll" resultType="com.example.mybatis01.entity.User">
        select * from user
    </select>
    <!-- 如果是多个参数,调用方法为#{0},#{1}... -->
    <select id="getById" resultType="com.example.mybatis01.entity.User" parameterType="Long">
        select * from user where id = #{id}
    </select>

</mapper>

第八步 方法调用

@RestController
public class UserController {
    @Autowired
    UserServiceImpl userService;

    @GetMapping("/list")
    public List<User> list() {
        return userService.selectAll();
    }

    @GetMapping("/getOne")
    public User getOne(Long id){
        return userService.getById(id);
    }
}

The end,查看效果。

list方法

getOne方法
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容