温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

MyBatis @Select注解怎么使用

发布时间:2022-07-11 13:59:32 来源:亿速云 阅读:1298 作者:iii 栏目:开发技术

这篇文章主要介绍“MyBatis @Select注解怎么使用”,在日常操作中,相信很多人在MyBatis @Select注解怎么使用问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”MyBatis @Select注解怎么使用”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

1、@Select注解基本用法

@Select注解的目的是为了取代xml中的select标签,只作用于方法上面。

下面看一下@Select注解的源码介绍:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Select
{
    String[] value();
}

从上述可以看到两点信息:

(1)@Select注解只能修饰方法

(2)@Select注解的值是字符数组。

所以,@Select注解的用法是这样的:

@Select({ "select * from xxx", "select * from yyy" })
Person selectPersonById(Integer id);

虽然@Select注解的值是字符数组,但是真正生效的应该是最后那条SQL语句。这一点请大家要留意一下。

2、@Select注解动态SQL拼写

普通的字符串值,只能实现变量的替换功能,如下所示,

@Select("select * from t_person where id = #{id}")
Person selectPersonById(Integer id);

如果要想实现复杂的逻辑判断,则需要使用标签,如下所示:

@Select("<script> select * from t_person where id = #{id} 
<when test='address !=null'> and address = #{address} 
</when> </script>")
Person selectPersonById(Integer id);

其实,标签并非是@Select注解专用的,其他的注解,例如@Insert,@Update等等,都可以使用的。

@Select动态参数参考

今天发现一个问题,使用标签进行查询语句的拼接时,逗号和引号老处理不好,所以在此记录下,供以后参考

    @Select("<script>" +
            " select * from tb_crowd_fund_person_record a,tb_crowd_fund_info b where b.id=a.crowd_fund_info_id " +
            " <if test='activeStatus != null and activeStatus != \"\"'> "+
            "  and b.active_status=#{activeStatus} " +
            " </if> " +
            " <if test='createUser != null and createUser != \"\"'> "+
            "  and a.create_user=#{createUser} " +
            " </if> " +
            "</script>")
    List<String> findByType(Map<String,String> map);

到此,关于“MyBatis @Select注解怎么使用”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI