@Select 注解的使用

作用

简便、快速去操作 sql

对一些简单的实现常见操作 sql 的应用:

1、 只需要在 mapper 中方法上加入 @Select(),然后在括号中写入需要实现的 sql 语句即可

例如:

@Select(“select \* from Type where id = #{id, jdbcType=LONG} and code= #{code, jdbcType=VARCHAR}”)  
Type selectTypeById(@Param(“id”) Long id, @Param(“code”) String code);

当然,上面的例子中 jdbcType 类型可以省略,只需字段的类型对齐好数据库中的字段类型即可。

2、 另外一种方式就是像我们通常写的 xml 类似,在注解中使用等相关的标签来实现我们复杂的语句,但是必须在外面一层用标签将 sql 语句含入进去

例如:

@Select("<script>select COUNT(p.ID) from MM_LIST p, USER c where p.USER_ID = #{userId} and p.USER_ID = c.ID <if test=“status != null and status != ‘’”>and p.STATUS = #{status}</if> <if test=“code!= null and code!= ‘’”>and p.CODE = #{code}</if></script>")
Long selectUserListCount(@Param(“code”) String code, @Param(“status”)String status, @Param(“userId”)Long userId);

但是这种注解的方式,对于条件较复杂的情况,不太建议这种方式,在字符串中难免会有很多错误,可读性很差。

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐