开发者社区> 问答> 正文

mybatis注解动态sql?报错

spring下使用mybatis注解方法实现dao,在@select 时使用动态sql select * from user where <if test=\"username !=null \">username = #{username} </if> <if test=\"phone !=null \">phone = #{phone} </if> <if test=\"usermail !=null \">usermail = #{usermail } </if>  查询时报错。

这种mybatis注解方法如何实现动态sql

展开
收起
爱吃鱼的程序员 2020-06-12 15:41:03 735 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB
    通过@SelectProvider实现一个拼装sql的类,解决问题  (用标签现在不写xml的配置文件标签是什么,我看用@SelectProvider拼接sql packagevo.mapper;importjava.util.List;importorg.apache.ibatis.annotations.Delete;importorg.apache.ibatis.annotations.Insert;importorg.apache.ibatis.annotations.Options;importorg.apache.ibatis.annotations.Param;importorg.apache.ibatis.annotations.Select;importvo.User;publicinterfaceUserMapper{@Insert("INSERTINTOuser(name,age,gender,experience)VALUES( #{name},#{age}, #{gender},#{experience})")@Options(useGeneratedKeys=true,keyProperty="id")intcreateUser(Useruser);@Insert("INSERTINTOuser_interest(user_id,interest_id)VALUES( #{userId},#{interestId})")intcreateUserInterest(@Param("userId")intuserId,@Param("interestId")intinterestId);@Delete("DELETEFROMuserWHEREid=#{id}")intdeleteUser(intid);@Delete("DELETEFROMuser_interestWHEREuser_id=#{userId}")intdeleteUserInterest(intuserId);//findUsers(String,int)的执行策略定义在UserMapper.xml中List<User>findUsers(@Param("name")Stringname,@Param("experience")intexperience);@Select("SELECTinterest_idFROMuser_interestWHEREuser_id=#{userId}ORDERBYid")List<Integer>findUserInterests(intuserId);//queryInterest(int,int)的执行策略定义在UserMapper.xml中List<User>queryInterest(@Param("gender")intgender,@Param("experience")intexperience);}



    不要xml文件,通过@SelectProvider实现一个拼装sql的类,解决问题楼上的也没解决楼主的问题啊

    更简单的方法是使用<script>标签直接包裹动态sql,用楼主的例子就是:

    @Select("<script>select*fromuserwhere<iftest=\"username!=null\">username=#{username}</if><iftest=\"phone!=null\">phone=#{phone}</if><iftest=\"usermail!=null\">usermail=#{usermail}</if></script>")

    这样定制性更大,实现起来也方便,记住这样做的话注解中的sql语句必须全都在<script>标签中



    所以还是使用xml配置会更好维护一些这样做似乎还没直接写到xml里好维护呢~
    2020-06-12 15:41:20
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
SQL Server云化思考与实践 立即下载
SQL Server在电子商务中的应用与实践 立即下载
Java Spring Boot开发实战系列课程【第6讲】:Spring Boot 2.0实战MyBatis与优化(Java面试题) 立即下载