springboot接入mybatis管理数据库
springboot接入mybatis管理数据库
-
1.创建springboot项目(使用开发工具类似IDEA新建Springboot项目)
-
2.pom依赖引入
<!-- mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!-- mybatis-spring-boot-starter --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>${mybatis.version}</version> </dependency>
-
3.配置文件(application.yml)
# 数据库配置 spring: datasource: # 驱动 driver-class-name: com.mysql.cj.jdbc.Driver # url url: jdbc:mysql://xxx:3306/second_kill?characterEncoding=utf-8&useSSL=false # 用户名 username: xxx # 密码 password: xxx dbcp2: # 验证查询 validation-query: select 1 from dual # MyBatis mybatis: # 包别名配置 type-aliases-package: com.kinson.springboot.domain # mapper xml位置配置 mapper-locations: classpath:/secondKill/*.xml # 控制台打印sql(https://www.cnblogs.com/kingsonfu/p/9245731.html) configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
-
4.启动类加MapperScan注解
@SpringBootApplication // 多个以逗号分隔 @MapperScan({"com.kinson.springboot.mapper", "xxx"}) public class SecondKillProSpringboot { public static void main(String[] args) { SpringApplication.run(SecondKillProSpringboot.class, args); } }
-
5.新加数据库表映射类
public class User { private Integer id; private String userName; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } }
-
6.新增对应的Mapper类
public interface UserMapper {
/** * 查询所有用户 * * @return */ List<User> selectUserList();
}
-
7.新增对应Mapper的映射xml文件
<select id="selectUserList" parameterType="User" resultMap="UserResult"> select * from user </select>
-
8.之后就可以使用mapper在service注入使用了
Github源码:springboot-mybatis
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理