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

作者:MyBatis中文官网 时间:2023-07-17 05:56:43 

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);

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。 

来源:http://www.mybatis.cn/archives/1010.html

标签:MyBatis,@Select注解,动态SQL
0
投稿

猜你喜欢

  • Idea2020.2创建JavaWeb项目(部署Tomcat)方法详解

    2023-11-02 13:29:52
  • 在idea中显示springboot面板的方法

    2022-01-02 22:00:57
  • 一文带你了解Java万物之基之Object类

    2023-10-09 01:58:28
  • Spring依赖注入的三种方式小结

    2022-08-09 15:56:41
  • Android实现系统重新启动的功能

    2021-06-04 02:48:56
  • 利用Flutter实现“孔雀开屏”的动画效果

    2021-11-04 21:24:17
  • 详解获取Spring MVC中所有RequestMapping以及对应方法和参数

    2023-12-09 21:29:17
  • edittext + listview 实现搜索listview中的内容方法(推荐)

    2022-03-11 21:41:57
  • android实现简单音乐播放器

    2021-06-28 22:07:26
  • Android实现ImageView图片双击放大及缩小

    2022-04-07 10:34:06
  • Java字符串操作和C#字符串操作的不同小结

    2022-02-15 07:21:14
  • C# goto语句的具体使用

    2021-07-22 22:26:22
  • java模拟http的Get/Post请求,并设置ip与port代理的方法

    2021-11-25 11:30:57
  • Spring AOP原理及动态代理

    2023-06-19 18:59:56
  • 解析ADT-20问题 android support library

    2023-06-19 22:20:20
  • java门禁系统面向对象程序设计

    2023-08-25 02:25:53
  • 详解Android MVP开发模式

    2022-04-13 08:30:43
  • Android基于google Zxing实现各类二维码扫描效果

    2022-04-10 17:28:59
  • Java-String类最全汇总(上篇)

    2023-04-15 11:47:10
  • C#生成验证码图片的方法

    2023-07-18 19:39:15
  • asp之家 软件编程 m.aspxhome.com