一个参数或一个对象
Dao层
public interface StudentDao {
int selectById(int id);
int insert(Student stu);
}
对应的mapper文件
<select id="selectById" resultMap="BaseResultMap">
select <include refid="Base_Column_List" />
from student
<where>
<if test="id != null">
id = #{id}
</if>
</where>
</select>
<insert id="insert" parameterType="com.yoho.crm.dal.model.student">
insert into student
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="username != null and username!= ''">user_name,</if>
<if test="age!= null">age,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="username != null and username!= ''">#{username},</if>
<if test="age!= null">#{age},</if>
</trim>
</insert>
多个参数
每个参数前加上@Param
注解,括号中注解的名称就是mapper中映射的值
import org.apache.ibatis.annotations.Param;
@Mapper
public interface CustomerInfoMapper extends BaseMapper<CustomerInfo> {
List<CustomerInfoVO> search(@Param("searchVal") String searchVal,
@Param("delegateCompany") String delegateCompany);
}
<select id="search" resultType="com.test.vo.CustomerInfoVO">
select a.*
from customer_info a
<where>
a.delete_flag=0
<if test="searchVal != null and searchVal != ''">
and a.company_name like CONCAT('%',#{searchVal},'%')
<!-- and a.company_name like CONCAT('%',#{param1},'%') -->
</if>
<if test="delegateCompany != null and delegateCompany != ''">
and a.company_name like CONCAT('%',#{delegateCompany},'%')
<!-- and a.company_name like CONCAT('%',#{param2},'%') -->
</if>
</where>
</select>
既有参数又有对象时
对象也需要注解,一般参数的直接取,对象的需要对象.属性
public interface SysMenuMapper extends BaseMapper<SysMenu> {
public List<SysMenu> selectMenuTreeByUserId(@Param("userId")Long userId,
@Param("menu")Menu menuSource);
}
注意,在动态sql里面也需要在判断的时候使用对象.属性
进行判断
<select id="selectMenuTreeByUserId" resultMap="SysMenuResult">
select *
from sys_menu m
where u.user_id = #{userId}
<!-- where u.user_id = #{param1} -->
<if test="menu.menuSource != null and menu.menuSource != ''">
AND m.menu_source = #{menu.menuSource}
</if>
<!-- <if test="param2.menuSource != null and param2.menuSource != ''"> -->
<!-- AND m.menu_source = #{param2.menuSource} -->
<!-- </if> -->
</select>