学习流程2025-01-04
1.springboot整合mybatis:
1.1idea创建spring项目,勾选web、jdbc、mysql
1.2集成mybatis:引入mybatis-spring-boot-starter
1.3配置文件里配置数据源:application.properties里:
# 配置数据源 spring.datasource.username=root spring.datasource.password=root spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8 # 目前较新版的mysql,使用带cj的com.mysql.cj.jdbc.Driver spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
1.4test类里进行验证mybatis集成是否成功:
@SpringBootTest class Springboot05MybatisApplicationTests { @Autowired private DataSource dataSource; @Test void contextLoads() { // 验证mybatis集成是否成功,若直接启动该测试方法会报错: // Failed to configure a DataSource: 'url' attribute is not specified // and no embedded datasource could be configured. // 需要先配置数据源(在application.properties里) // 验证结果:如下输出:dataSource.getClass(): class com.zaxxer.hikari.HikariDataSource System.out.println("dataSource.getClass(): " + dataSource.getClass()); try { // 验证结果:如下输出:dataSource.getConnection(): // HikariProxyConnection@1871778598 wrapping // com.mysql.cj.jdbc.ConnectionImpl@f1d0004 System.out.println("dataSource.getConnection(): " + dataSource.getConnection()); } catch (SQLException e) { e.printStackTrace(); } } }
1.5实体类:
@Data @AllArgsConstructor @NoArgsConstructor public class User { private int id; private String name; private String pwd; }
1.6Mapper接口:
// @Mapper表明是mybatis的一个Mapper接口 // 加上@Repository后可以被spring识别, // 对普通java类用@Component,对dao层用@Repository更合适 @Mapper @Repository public interface UserMapper { public List<User> getAllUsers(); public User getUserById(int id); }
1.7mapper的xml文件:
<?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"> <!-- 配置namespace --> <mapper namespace="com.example.mapper.UserMapper"> <select id="getAllUsers" resultType="User"> select * from mybatis.user </select> <select id="getUserById" resultType="User"> select * from mybatis.user where id = #{id} </select> </mapper>
1.8配置文件里配置typealiases别名和mybatis xml文件位置:application.properties里:
# 配置 # 一开始我写的是错的:配置的mapper:mybatis.type-aliases-package=com.example.mapper # 这里应该配置的是实体类:com.example.pojo mybatis.type-aliases-package=com.example.pojo # 配置mapper文件位置: mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
1.9用于验证的controller:
@RestController public class UserController { @Autowired private UserMapper userMapper; @RequestMapping("/getAllUsers") public List<User> getAllUsers() { List<User> users = userMapper.getAllUsers(); for (User user : users) { System.out.println(user.toString()); } return users; } @RequestMapping("/getUserById") public User getUserById() { return userMapper.getUserById(1); } }
标签:01,spring,流程,2025,dataSource,mysql,mybatis,com,public From: https://www.cnblogs.com/pingfanliliang/p/18654019