mybatis中mapper文件判断属性是否为空

在mybatis的mapper文件中判断对象属性或者字符串是否为空的时候常用以下判断条件:

<if test="type!=null and type!=''">  

    AND type = #{type}  
</if>  
### MyBatis Mapper 映射文件详解 #### 1. XML 文件配置方法 MyBatis 支持通过 XML 文件来定义 SQL 映射语句。Mapper 文件通常位于项目的 `resources` 目录下,文件名一般与接口类同名并以 `.xml` 结尾。 ```xml <mapper namespace="com.example.mapper.UserMapper"> <!-- 定义一个名为 userResultMap 的 resultMap --> <resultMap id="userResultMap" type="com.example.model.User"> <id property="id" column="user_id"/> <result property="username" column="user_name"/> <result property="password" column="user_password"/> </resultMap> <!-- 查询单个用户的 SQL 语句 --> <select id="getUserById" parameterType="int" resultMap="userResultMap"> SELECT * FROM users WHERE user_id = #{userId} </select> </mapper> ``` 这段代码展示了如何创建一个名为 `userResultMap` 的结果映射,并将其用于查询操作中[^1]。 #### 2. Result Map 和 Result Type 在 MyBatis 中可以使用两种方式指定返回类型的映射:`<resultMap>` 和 `resultType` 属性。其中 `<resultMap>` 提供更灵活的方式处理复杂的字段映射关系;而 `resultType` 则适用于简单场景下的直接映射[^2]。 对于较为复杂的数据结构转换需求来说,推荐优先考虑采用 `<resultMap>` 来实现定制化的映射逻辑: ```xml <!-- 复杂关联表映射示例 --> <resultMap id="orderDetailResultMap" type="OrderDetail"> <association property="productInfo" javaType="Product"> <id property="productId" column="prod_id"/> ... </association> <collection property="items" ofType="Item"> <id property="itemId" column="item_id"/> ... </collection> </resultMap> ``` 这里展示了一个订单详情 (`OrderDetail`) 对象与其子项列表之间的嵌套映射关系[^4]。 #### 3. 动态 SQL 构建 为了提高灵活性和支持更多业务逻辑变化,在实际开发过程中经常需要用到动态 SQL 特性。可以通过内置标签如 `<if>`, `<choose>`, `<when>`, `<otherwise>` 等构建条件判断式的 SQL 表达式。 例如下面的例子实现了基于不同参数组合生成不同的查询条件的功能: ```xml <select id="findUsersByConditions" parameterType="map" resultType="User"> SELECT * FROM users u <where> <if test="name != null and name != ''"> AND u.name LIKE CONCAT('%',#{name},'%') </if> <if test="age != null"> AND u.age >= #{age} </if> </where> </select> ``` 此片段说明了当传入特定名称或年龄范围作为筛选条件时,能够自动调整最终执行的 SQL 文本。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值