Dao层传递参数到mapping.xml文件的几种方式

 Dao层传递参数到mapping.xml文件的几种方式:(Mybatis传值总结)

第一种:传递单个参数

Dao层Code片段:

/**
* 根据articleId查询XXXX详情.
* @param articleId
* @return {@link CmsProductArticle}
*/

public CmsProductArticle getCmsProductArticleByArticleId(Long articleId);
Mapping片段:
SELECT * 
FROM tableA a, tableB b
WHERE a.article_id = b.article_id
and a.del_flag != 2
and b.article_id = #{articleId}
说明:传递单个参数时直接将parameterType设置成你传入的参数类型(Long),直接用“#{}”获得参数,参数名必须与Dao层参数名一致。

resultType是SQL查询结果返回的类型,Dao层接口返回是实体类,所以这里的resultType是实体类的路径

第二种:传递多个参数

1,以注解标记

Dao层Code片段:

/**
* 查询companyId是否存在.
* @param companyId
* @param imgId
* @return int
*/
public int queryCompanyIdAndImgIdIsExist(@Param("companyid") Long companyId, @Param("id") Long imgId);

Mapping片段:

select count(1)
from table_img img
where img.company_id = #{companyid}
and img.id = #{id}

说明:此时不需要写parameterType,但是注意“#{}”内的参数名必须跟你在Dao层中注解@Param("")内定义的名称一致。

2,直接传递参数

Dao层Code片段:

/**
* 查询companyId是否存在.
* @param companyId
* @param imgId
* @return int
*/
public int queryCompanyIdAndImgIdIsExist( Long companyId,  Long imgId);

Mapping片段:

select count(1)
from table_img img
where img.company_id = #{0}
and img.id = #{1}

说明:#{0}与#{1}是你在Dao里的参数顺序,参数名可以不一样,注重顺序

3,以Map传递参数

实现类Service片段:

Map searchCondition = new HashMap<>();
searchCondition.put("categoryId", categoryId);
searchCondition.put("status", status);
List cmsProductArticles = cmsProdcutArticleDao.getCmsProductArticles(searchCondition);

Dao层Code片段:

/**
* 根据搜索条件查询产品模板集.
* @param searchCondition
* @return List
*/

public List getCmsProductArticles(Map searchCondition);

Mapping片段:

SELECT *
FROM table a, table b
WHERE a.article_id = b.article_id
and a.del_flag != 2
and a.category_id = #{categoryId}
and a.status = #{status}

说明:#{categoryId}、#{status}对应你在Map里面的Key

第三种:以实体类传递

Dao层Code片段:

/**
* 更新
* @param cmsProductArticle
* @return
*/
public void updateCmsProductArticle(CmsProductArticle cmsProductArticle);

Mapping片段:

UPDATE table
SETcategory_id = #{categoryId}, supply_type = #{supplyType}, pay_type = #{payType}, pay_value = #{payValue}, status = #{status}
WHERE article_id = #{articleId}
and del_flag != 2

说明:#{categoryId}等对应实体类中属性。

你可能感兴趣的:(Java,java,xml)