spring boot 扫描dao 接口同目录下的 mapper文件

类似于下图中,dao接口 和 mapper文件在同一个目录下。按照spring boot 常规配置,mapper文件应该写在 resources 文件夹下。

springboot 常规扫描 mapper文件的写法:

mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
如果mapper 文件 和 dao接口在同目录下,需要两步,
1.则修改配置:classpath后要加 星号
mybatis.mapper-locations=classpath*:com/example/demo/dao/*.xml

2.修改 pom 文件,在 build 节点下 添加如下配置

        <!-- ......用于扫描 dao 文件下的mapper 文件................. start -->
        <resources>
            <resource>
                <!--编译 src/main/resources 下的配置文件-->
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
            </resource>

            <!-- 编译 src/main/java 目录下的 mapper 文件 -->
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
         <!-- ......用于扫描 dao 文件下的mapper 文件................. end -->

 

Spring Boot中,通常使用MyBatis框架作为数据访问层(DAO)。MyBatis是一个持久层框架,它可以使用XML文件或注解来进行SQL语句的映射和执行。下面是使用XML文件连接MyBatis和Spring Boot的步骤: 1. 添加MyBatis和MyBatis-Spring依赖项到项目中: ```xml <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.4</version> </dependency> ``` 2. 在application.properties文件中配置数据库连接信息: ```properties spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver ``` 3. 在DAO接口中定义需要执行的SQL语句: ```java public interface UserDao { @Select("SELECT * FROM user WHERE id = #{id}") User getUserById(Integer id); } ``` 4. 在resources目录下创建mybatis映射文件UserMapper.xml,并在其中定义SQL语句的映射: ```xml <mapper namespace="com.example.dao.UserDao"> <select id="getUserById" parameterType="java.lang.Integer" resultType="com.example.entity.User"> SELECT * FROM user WHERE id = #{id} </select> </mapper> ``` 5. 在application.properties文件中指定mybatis映射文件的位置: ```properties mybatis.mapper-locations=classpath*:mapper/*.xml ``` 6. 在Spring Boot启动类上添加@MapperScan注解,指定MyBatis的Mapper接口所在的包名: ```java @SpringBootApplication @MapperScan("com.example.dao") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 这样就完成了XML文件DAO层的连接。在需要使用DAO层的地方,只需要使用@Autowired注解将DAO层注入即可使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值