您的位置:首页 > 健康 > 美食 > mybatisplus 通过xml 定义接口

mybatisplus 通过xml 定义接口

2024/10/7 5:52:47 来源:https://blog.csdn.net/mybluesky1983/article/details/141327151  浏览:    关键词:mybatisplus 通过xml 定义接口

在 MyBatis-Plus 中,虽然它极大地简化了 CRUD 操作,提供了许多注解方式(如 @Select@Insert@Update@Delete)来直接在 Mapper 接口上定义 SQL 语句,但 MyBatis-Plus 仍然支持传统的 MyBatis 风格的 XML 配置方式来定义 SQL 语句。这种方式提供了更大的灵活性和复杂 SQL 的处理能力。

1. 创建 Mapper 接口

首先,你需要创建一个 Mapper 接口,这个接口会包含你需要执行的数据库操作方法。比如,你有一个 UserMapper 接口来操作用户表。

package com.example.mapper;  import com.baomidou.mybatisplus.core.mapper.BaseMapper;  
import com.example.entity.User;  
import org.apache.ibatis.annotations.Mapper;  @Mapper  
public interface UserMapper {  // 这里可以定义你自己的方法,然后通过 XML 映射 SQL  User selectUserById(Long id);  
}

2. 创建 XML 映射文件

然后,你需要为上述的 Mapper 接口创建一个 XML 映射文件。这个文件通常与 Mapper 接口在同一个包路径下,但位于 resources 目录下的 mapper 文件夹中(这个文件夹的路径可以根据你的项目配置来调整)。

例如,如果你的 Mapper 接口在 com.example.mapper 包下,那么 XML 文件可能位于 src/main/resources/mapper/UserMapper.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">  
<mapper namespace="com.example.mapper.UserMapper">  <!-- 根据ID查询用户 -->  <select id="selectUserById" resultType="com.example.entity.User">  SELECT * FROM user WHERE id = #{id}  </select>  </mapper>

3. 配置 MyBatis-Plus

确保你的 MyBatis-Plus 配置已经正确设置了 mapper 文件的路径。如果你使用的是 Spring Boot 集成 MyBatis-Plus,那么通常这个配置会在 application.properties 或 application.yml 文件中自动配置好,因为 Spring Boot 会根据约定大于配置的原则来寻找 mapper 接口和 XML 文件。

但是,如果你需要手动配置,确保 MyBatis 的配置文件(如 mybatis-config.xml)中包含了 mapper 文件的路径,或者你的 Spring Boot 应用通过 @MapperScan 注解指定了 mapper 接口的扫描路径。

mybatis-plus:mapper-locations: classpath:mapper/*.xml

4. 使用 Mapper

一旦 Mapper 接口和 XML 文件配置完成,你就可以在你的服务层或控制器中注入 UserMapper 并调用其方法来执行数据库操作了。

@Service  
public class UserService {  @Autowired  private UserMapper userMapper;  public User getUserById(Long id) {  return userMapper.selectUserById(id);  }  
}

这就是在 MyBatis-Plus 中通过 XML 文件定义 Mapper 接口的 SQL 语句的基本步骤。这种方式让你能够编写复杂的 SQL 语句,同时享受 MyBatis-Plus 提供的强大功能。

如果报错 Invalid bound statement (not found)  请参考

https://www.cnblogs.com/zhoushiya/p/12797240.html

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com