spring boot整合mybatis框架

2025-04-06 06:48:28

1、推荐使用intellij idea作为开发工具,使用intellij idea创建spring boot框架,如下图所示,添加maven依赖,代码如下 <dependenc烤恤鹇灭y> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency>

spring boot整合mybatis框架

2、创建一个TestMapper.java文件,代码如下/*** Created by zuli on 2018/10/10.*/public interface TestMapper { int test();}

3、在resources目录下创建TestMapper.xml文件,代码如下<?垓矗梅吒xml version="1.0" enco颊俄岿髭ding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.zuli.mapper.TestMapper"> <select id="test" resultType="int"> SELECT 1 FROM DUAL </select></mapper>

spring boot整合mybatis框架

4、添加@MapperScan()注解,配置basePackages属性,代码如下@SpringBoot帆歌达缒Application@MapperScan(basePackages = "com.zuli.mapper")public class SpringBootMybatisApplication { public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(SpringBootMybatisApplication.class, args); TestMapper testMapper = context.getBean(TestMapper.class); System.out.println(testMapper.test()); }}

spring boot整合mybatis框架

5、修改application.properties配置文件,配置数据源,mapper xml文件路径等代码如下spring.datasource.url=jdbc:mysql://localhost/testspring.datasource.username=rootspring.datasource.password=123456spring.datasource.driver-class-name=com.mysql.jdbc.Drivermybatis.mapper-locations=classpath:*Mapper.xml

spring boot整合mybatis框架

6、启动应用程序,调用TestMapper的test()方法,打印日志,如下图所示

spring boot整合mybatis框架

7、整体demo的项目结构如下图所示

spring boot整合mybatis框架
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢