MyBatis @Select注解介绍:基本用法与动态SQL拼写 您所在的位置:网站首页 select和choose有啥区别 MyBatis @Select注解介绍:基本用法与动态SQL拼写

MyBatis @Select注解介绍:基本用法与动态SQL拼写

2023-08-31 08:25| 来源: 网络整理| 查看: 265

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(" select * from t_person where id = #{id} and address = #{address} ") Person selectPersonById(Integer id);

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

3、参考:

MyBatis @Select注解介绍:基本用法与动态SQL拼写



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有