Springboot3整合Mybatis3的完整步骤记录
作者:(前程似锦)
这篇文章主要给大家介绍了关于Springboot3整合Mybatis3的完整步骤,Spring Boot和MyBatis分别是两个功能强大的框架,它们的协同使用可以极大地简化数据访问层的开发,提高整体的开发效率,文中通过代码介绍的非常详细,需要的朋友可以参考下
一、导入依赖
mybatis 的必要依赖
注意:使用 springboot3 的话要使用 mybatis3 的版本以及 java17及以上的版本
<!-- mybaitis 依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<!--mysql链接依赖-->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
二、编写配置文件
server:
port: 8081
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/user?serverTimezone=GMT%2B8&characterEncoding=utf-8&useSSL=false
username: root
password: 200718
mybatis:
# mapper映射文件包扫描 (这里是对应 resources 的文件路径)
mapper-locations: classpath:/mappers/*.xml
# 实体类别名包扫描
type-aliases-package: com.yun.pojo
三、定义模型 entity 实体类
@AllArgsConstructor
@NoArgsConstructor
@Data
public class User {
private int id;
private String username;
private String password;
}四、在启动类上添加注解,表示mapper接口所在位置
注意: 如果接口上面有 注解 @Mapper 的话,就可以不用在使用扫描包注解 @MapperScan 了(当然两个可以同时存在)
@SpringBootApplication
@MapperScan("com.example.mybaitis_01.mapper") // 扫描的mapper
public class Mybaitis01Application {
public static void main(String[] args) {
SpringApplication.run(Mybaitis01Application.class, args);
}
}
五、定义mapper接口
注意: 最好要加上 @Mapper注解,防止忘记开启扫描
@Mapper
public interface TestMapper {
List<String> selectNameAll();
}
六、定义mapper.xml映射文件
注意:头文件这里的网站链接是没有 www 的,且能识别到 文件时,里面的 SQL 是有颜色的,否则就是白色
<?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.yun.mappers.TestMapper">
<select id="selectNameAll" resultType="com.yun.pojo.User">
select * from tb_user
</select>
</mapper>
七、service层
注意: 接口和实现类最好把 @Service 加上,否则会出现找不到 bean 的问题
1、接口:
@Service
public interface TestService {
List<String> selectNameAll();
}
2、实现类:
@Service
public class TestServiceImpl implements TestService {
@Autowired
private TestMapper testMapper;
@Override
public List<String> selectNameAll() {
return testMapper.selectNameAll();
}
}
八、测试
这里测试是调用Service层的,也可以调用Mapper层来实现 查询
@SpringBootTest
class Demo1ApplicationTests {
@Autowired
private TestService testService;
@Test
void contextLoads() {
System.out.println(testService.selectNameAll());
}
}补充:Springboot中Mybatis属性映射--开启驼峰命名
mybatis默认是属性名和数据库字段名一一对应的,即
- 数据库表列:user_name
- 实体类属性:user_name
但是java中一般使用驼峰命名
- 数据库表列:user_name
- 实体类属性:userName
在Springboot中,可以通过设置map-underscore-to-camel-case属性为true来开启驼峰功能。
application.yml中:
mybatis:
configuration:
map-underscore-to-camel-case: true
application.properties中:
mybatis.configuration.map-underscore-to-camel-case=true
总结
到此这篇关于Springboot3整合Mybatis3的文章就介绍到这了,更多相关Springboot3整合Mybatis3内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
