Mybatis传递多个参数的几种方式

 

#{}是占位符,预编译处理;${}是拼接符,字符串替换,没有预编译处理。
#{} 可以有效的防止SQL注入,提高系统安全性;${} 不能防止SQL 注入
#{} 的变量替换是在DBMS 中;${} 的变量替换是在 DBMS 外

 

顺序传参法

public User selectUser(String name, int deptId);

<select id="selectUser" resultMap="UserResultMap">
    select * from user
    where user_name = #{0} and dept_id = #{1}
</select>

#{}里面的数字代表你传入参数的顺序。

这种方法不建议使用,sql层表达不直观,且一旦顺序调整容易出错。

@Param注解传参法

public User selectUser(@Param("userName") String name, int @Param("deptId") deptId);

<select id="selectUser" resultMap="UserResultMap">
    select * from user
    where user_name = #{userName} and dept_id = #{deptId}
</select>

#{}里面的名称对应的是注解@Param括号里面修饰的名称。

这种方法在参数不多的情况还是比较直观的,推荐使用。

Map传参法

public User selectUser(Map<String, Object> params);

<select id="selectUser" parameterType="java.util.Map" resultMap="UserResultMap">
    select * from user
    where user_name = #{userName} and dept_id = #{deptId}
</select>

#{}里面的名称对应的是Map里面的key名称。

这种方法适合传递多个参数,且参数易变能灵活传递的情况。

PS:
MyBatis传递map参数时,如果传递参数中没有对应的key值,在执行sql语句时默认取的是null

例如:map中没有put “name”这个key,在sql中使用#{name}时,默认赋值null

Java Bean传参法

public User selectUser(User params);

<select id="selectUser" parameterType="com.test.User" resultMap="UserResultMap">
    select * from user
    where user_name = #{userName} and dept_id = #{deptId}
</select>

#{}里面的名称对应的是User类里面的成员属性。

这种方法很直观,但需要建一个实体类,扩展不容易,需要加属性,看情况使用。

 

 

 

SELECT top 10000 tol.TuhuCost,tol.BaseCost,tol.OrderID AS OrderListOrderID,torp.ChildrenOrderId, torp.ParentOrderId,tol.pkid as OrderListID,torp.RelationshipType,tor.InstallShopID,tor.WareHouseID
FROM dbo.tbl_OrderRelationship AS torp WITH(NOLOCK)
LEFT JOIN dbo.tbl_OrderList AS tol WITH(NOLOCK)
ON torp.ParentOrderId = tol.OrderID
left JOIN vw_tbl_order as tor ON torp.ParentOrderId=tor.PKID
WHERE torp.CreateDatetime>='2019-11-29'
AND torp.RelationshipType = 1
AND tor.InstallShopID IS NOT NULL
AND tor.InstallShopID<>tor.WareHouseID
AND tor.Status<>'7Canceled'
AND tol.TuhuCost is not NULL
ORDER BY torp.CreateDatetime DESC

 

SELECT COUNT (1) as cnt FROM (
SELECT DISTINCT tol.OrderID
FROM dbo.tbl_OrderRelationship AS torp WITH(NOLOCK)
LEFT JOIN dbo.tbl_OrderList AS tol WITH(NOLOCK)
ON torp.ParentOrderId = tol.OrderID
left JOIN vw_tbl_order as tor ON torp.ParentOrderId=tor.PKID
WHERE torp.CreateDatetime>='2019-11-29'
AND torp.RelationshipType = 1
AND tor.InstallShopID IS NOT NULL
AND tor.InstallShopID<>tor.WareHouseID
AND tor.Status<>'7Canceled' AND tol.baseCost=0
AND tol.TuhuCost is not NULL ) as t1

 

SELECT COUNT(1) as cnt from tbl_orderlist as t1 with(nolock)  left join vw_tbl_order as t2 with(nolock) ON t1.orderid=t2.pkid WHERE t2.OrderDatetime>='2019-12-01'  AND t1.cost>0 AND t1.baseCost=0

 

posted @ 2019-07-19 13:49  张龙豪  阅读(3484)  评论(0编辑  收藏  举报