SpringBoot集成MyBatis
属于数据访问层;MyBatis所有的包都是自己的,所以要导入自己的依赖
1、导入驱动和依赖
<!-- 这是自定义的包 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<!-- mysql 驱动 可以用自己的版本-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
2、编写配置文件:application.yaml(在resources目录下)
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://3306/mybatis?useSSL=true&userUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.jdbc.Driver
# mysql5 com.mysql.jdbc.Driver
# mysql8 com.mysql.cj.jdbc.Driver 必须要在url连接中编写时区 serverTimezone=UTC
3、测试数据源是否已经配置成功,在测试类中测试
package com.star;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
@SpringBootTest
class SpringbootApplicationTests {
// 自动导入数据源
@Autowired
private DataSource dataSource;
@Test
void contextLoads() throws SQLException {
//查看默认数据源 class com.zaxxer.hikari.HikariDataSource
System.out.println(dataSource.getClass());
//获取连接
Connection connection = dataSource.getConnection();
//关闭
connection.close();
}
}
SpringBoot 目前默认的数据源是 class com.zaxxer.hikari.HikariDataSource
4、编写实体类
package com.star.pojo;
import lombok.Data;
@Data
public class User {
private int id;
private String name;
private String pwd;
}
5、编写mapper接口(使用注解或者xml都可以)
package com.star.mapper;
import com.star.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper //标注这个一个mapper接口
@Repository //代表持久层
public interface UserMapper {
// @Value("select * from user")
List<User> getUserList();
}
配置文件中要添加mybatis配置
mybatis:
type-aliases-package: com.star.pojo
mapper-locations: classpath:com/star/mapper/*.xml
6、编写资源过滤
<!--配置资源过滤-->
<resources>
<resource>
<filtering>true</filtering>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
7、编写测试类
package com.star.controller;
import com.star.mapper.UserMapper;
import com.star.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class MyBatisController {
@Autowired //自动注入接口
private UserMapper userMapper;
@RequestMapping("list")
public List getUserList(){
List<User> userList = userMapper.getUserList();
return userList;
}
}
测试结果:
我们可得出结论:只需要编写对应的配置文件,导入对应的依赖就可以用了!
原文地址:https://www.cnblogs.com/lmx-181028/p/12411935.html
时间: 2024-11-14 14:15:45