这篇文章主要介绍了MyBatis @Select注解介绍:基本用法与动态SQL拼写方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
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注解介绍:基本用法与动态SQL拼写方式
猜你喜欢
- ExecutorService Callable Future多线程返回结果原理解析 2023-06-01
- JSP页面间传值问题实例简析 2023-08-03
- Java中的日期时间处理及格式化处理 2023-04-18
- 基于Java Agent的premain方式实现方法耗时监控问题 2023-06-17
- Springboot整合minio实现文件服务的教程详解 2022-12-03
- JSP 制作验证码的实例详解 2023-07-30
- Spring Security权限想要细化到按钮实现示例 2023-03-07
- SpringBoot使用thymeleaf实现一个前端表格方法详解 2023-06-06
- Java实现顺序表的操作详解 2023-05-19
- 深入了解Spring的事务传播机制 2023-06-02