• SpringBoot整合MyBatis


    一、准备工作

    1、建表语句,使用MySQL5.7.28

    SET FOREIGN_KEY_CHECKS=0;
    
    -- ----------------------------
    -- Table structure for t_user
    -- ----------------------------
    DROP TABLE IF EXISTS `t_user`;
    CREATE TABLE `t_user` (
      `ID` int(11) NOT NULL AUTO_INCREMENT COMMENT '序号',
      `USER_NAME` varchar(32) DEFAULT NULL COMMENT '用户名',
      `PASSWORD` varchar(32) DEFAULT NULL COMMENT '密码',
      `ROLES` varchar(255) DEFAULT NULL COMMENT '角色信息',
      PRIMARY KEY (`ID`)
    ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
    
    -- ----------------------------
    -- Records of t_user
    -- ----------------------------
    INSERT INTO `t_user` VALUES ('1', 'zhangsan', '123456', 'admin,user');

    2、导入pom.xml依赖

    MyBatis对SpringBoot的支持

    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.0.1</version>
    </dependency>

    MySQL驱动程序

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.20</version>
    </dependency>

    3、连接配置,建议使用application.yml

    spring:
      datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/pos?useUnicode=true&characterEncoding=utf-8
        username: root
        password: root

    二、整合MyBatis(注解)

    1、新建实体类

    @Data
    @AllArgsConstructor
    public class User {
        private String id;
        private String userName;
        private String password;
        private String roles;
    }

    2、新建映射接口

    @Mapper
    public interface UserMapper {
        @Select("SELECT * FROM t_user WHERE USER_NAME = #{name}")
        User getUserByName(String name);
    }

    3、测试

    @SpringBootTest
    class WmsMainApplicationTests {
    
        @Autowired
        private UserMapper userMapper;
    
        @Test
        void getUserByName() {
            String name = "zhangsan";
            User user = userMapper.getUserByName(name);
            System.out.println(user);
        }
    }

    4、输出

     可在配置文件中开启sql语句显示

    logging:
      level:
      #指定包名 springbootwms: debug
  • 相关阅读:
    __weak
    c++界面设计皮肤工具
    执行游戏时出现0xc000007b错误的解决方法
    2.4.1-Java语言基础(常量)
    句法模式识别(一)-串文法
    一步一步写算法(之hash表)
    LaTeX新人教程,30分钟从全然陌生到基本入门
    初次当面试官的经历和感触
    Android入门第八篇之GridView(九宫图)
    Android-Cannot merge new index 66195 into a non-jumbo instruction的解决的方法
  • 原文地址:https://www.cnblogs.com/liquorppp/p/12844385.html
Copyright © 2020-2023  润新知