一、准备工作
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、新建实体类
//java框架 www.1b23.com @Data @AllArgsConstructor public class User { private String id; private String userName; private String password; private String roles; }
2、新建映射接口
//java框架 www.1b23.com @Mapper public interface UserMapper { @Select("SELECT * FROM t_user WHERE USER_NAME = #{name}") User getUserByName(String name); }
3、测试
//java框架 www.1b23.com @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