
🍬 SpringBoot MyBatis
💬 MyBatis简介
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生类型、接口和 Java 的 POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
🌌 使用MyBatis
🛑 添加必要的依赖
1 2 3 4 5 6 7 8 9 10
| <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.48</version> </dependency>
|
📑 修改配置文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| server: port: 8080 servlet: context-path: /
spring: datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/springboot?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8 username: root password: root
mybatis: mapper-locations: classpath:mapper/*.xml type-aliases-package: com.longhujing.springboot.study.mybatis.entity
logging: level: com.longhujing.springboot.study.mybatis: debug
|
🌈 生成代码
实在不想做这种没有意义的体力劳动,所以使用MyBatis Generator来生成代码,具体的做法可以参考我的文章《IDEA使用MyBatis Generator自动生成代码》
☔ 修改启动类,添加一个注解
1 2 3 4 5 6 7 8 9
| @SpringBootApplication @MapperScan(basePackages = "com.longhujing.springboot.study.mybatis.mapper") public class SpringbootStudyMybatisApplication {
public static void main(String[] args) { SpringApplication.run(SpringbootStudyMybatisApplication.class, args); }
}
|
🎄 测试MyBaits
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| package com.longhujing.springboot.study.mybatis;
import com.longhujing.springboot.study.mybatis.entity.UserEntity; import com.longhujing.springboot.study.mybatis.mapper.UserEntityMapper; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest class SpringbootStudyMybatisApplicationTests {
@Autowired private UserEntityMapper userEntityMapper;
@Test void contextLoads() { UserEntity userEntity = userEntityMapper.selectByPrimaryKey(1L); System.out.println(userEntity.getName()); }
}
|