在SpringBoot中自定义sql语句

本文介绍如何在SpringBoot项目中使用MyBatis自定义SQL语句,通过@Select和@Update等注解实现复杂查询及更新操作,并提供具体接口方法示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关于在SpringBoot中自定义Sql语句


@Mapper
public interface MessageMapper {
    int countByExample(MessageExample example);

    int deleteByExample(MessageExample example);

    int deleteByPrimaryKey(String id);

    int insert(Message record);

    int insertSelective(Message record);

    List<Message> selectByExample(MessageExample example);

    Message selectByPrimaryKey(String id);

    int updateByExampleSelective(@Param("record") Message record, @Param("example") MessageExample example);

    int updateByExample(@Param("record") Message record, @Param("example") MessageExample example);

    int updateByPrimaryKeySelective(Message record);

    int updateByPrimaryKey(Message record);

    @Select("select *,count(*) as count from message WHERE toid = #{userId} GROUP BY formid ORDER BY created_date desc limit #{offset}, #{limit}")
    List<Message> selectConversationList(@Param("userId") String userId, @Param("offset") int offset, @Param("limit") int limit);

    @Update("update message set has_read = 1 where conversation_id = #{conversationId}")
    void updateMessageHasReadByConversationId(@Param("conversationId") String conversationId);
}
}

上面代码中selectConversationList()就是自定义的Sql,只需要在方法的上面加上注解@Select即可,当然还有其他的例如Delete,Update。参数怎样定义在上面也有写到

### 使用 Spring Boot 和 MyBatis 编写带有自定义 SQL 注解的 Mapper 接口 在 Spring Boot 中集成 MyBatis 后,可以通过 `@Select`、`@Insert`、`@Update` 或者 `@Delete` 等注解,在 Mapper 接口中直接编写 SQL 语句。这种方式使得开发人员可以在不依赖 XML 文件的情况下完成数据访问层的功能实现。 #### 配置 MyBatis 扫描路径 为了使应用程序能够找到所有的 Mapper 接口并加载相应的 SQL 映射文件(如果有的话),需要在 application.yml 或 application.properties 中设置扫描位置: ```yaml mybatis: mapper-locations: classpath:mapper/*.xml ``` 此配置指定了 MyBatis 将会查找位于 resources/mapper/ 下的所有 .xml 文件作为映射资源[^1]。 #### 创建 Mapper 接口 下面展示了如何创建一个名为 `UserMapper` 的接口,并利用 MyBatis 提供的各种注解来定义方法及其对应的 SQL 逻辑: ```java package com.example.demo.mapper; import org.apache.ibatis.annotations.*; import java.util.List; import com.example.demo.model.User; @Repository public interface UserMapper { // 定义查询所有用户的SQL语句 @Select("SELECT * FROM users") List<User> findAll(); // 基于ID获取单个用户信息 @Select("SELECT * FROM users WHERE id = #{id}") User findById(@Param("id") Long userId); // 插入新记录到数据库中 @Insert("INSERT INTO users(name, email) VALUES(#{name}, #{email})") int insertUser(@Param("name") String name, @Param("email") String email); // 更新现有记录的信息 @Update("UPDATE users SET name=#{user.name}, email=#{user.email} WHERE id=#{user.id}") void updateUser(@Param("user") User user); // 删除特定ID对应的数据项 @Delete("DELETE FROM users WHERE id = #{id}") void deleteUserById(@Param("id") Long userId); } ``` 上述代码片段中的每一个方法都关联了一条具体的 SQL 操作命令,这些命令会在调用相应的方法时被执行。此外,还使用了 `@Param` 来明确参数名称以便更好地匹配占位符变量[^4]。 #### 测试功能 一旦完成了上面提到的工作之后就可以像平常一样注入这个 Mapper 并对其进行单元测试验证其正确性了。 ```java @SpringBootTest class DemoApplicationTests { @Autowired private UserMapper userMapper; @Test void contextLoads() { System.out.println((Object) this.userMapper.findAll()); } } ``` 通过这样的方式可以快速搭建起基于 Spring Boot 和 MyBatis 的应用框架,并且实现了对数据库的操作而无需额外维护 XML 形式的 SQL 脚本文件[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值