1. 程式人生 > >MyBatis傳入引數的方式

MyBatis傳入引數的方式

以下是傳入兩個引數的方式:

第一種,使用@Param註解,定義引數別名,即定義對映關係
DAO:	 
public List<User> findByUsernameAndPwd(@Param("userNameABC") String username, @Param("passWordDEF") String password);
SQL:
 <select id="findByUsernameAndPwd" resultMap="resultMap">
	SELECT
	<include refid="columnSql"></include>
	FROM t_user
	<where>
		<if test="userNameABC !=null and userNameABC != '' ">and username =#{userNameABC}</if>
		<if test="passWordDEF !=null and passWordDEF != '' ">and password = #{passWordDEF}</if>
	</where>
</select>

第二種,直接傳入引數,SQL中需要使用param1,param2,param3...(使用arg0,arg1,arg2...報錯)
//Available parameters are [0, 1, param1, param2]。傳入第三個引數使用param3,親測可用。
DAO: 
public List<User> findByUsernameAndPwd(String username, String password);
SQL:
 <select id="findByUsernameAndPwd" resultMap="resultMap">
	SELECT
	<include refid="columnSql"></include>
	FROM t_user
	<where>
		<if test="param1 !=null and param1 != '' ">and username =#{param1}</if>
		<if test="param2 !=null and param2 != '' ">and password =#{param2}</if>
	</where>
</select>

第三種,在SERVICE中定義成Map,SQL使用引數的Key
SERVICE:
public List<User> findByUsernameAndPwd(String name, String pwd) {
	Map<String,Object> map = new HashMap<String,Object>();
	map.put("userNameABC",name);
	map.put("passWordDEF",pwd);
	return userDao.findByUsernameAndPwd(map);
}
DAO:
public List<User> findByUsernameAndPwd(Map<String,Object> map);
SQL:
<select id="findByUsernameAndPwd" resultMap="resultMap">
	SELECT
	<include refid="columnSql"></include>
	FROM t_user
	<where>
		<if test="userNameABC !=null and userNameABC != '' ">and username =#{userNameABC}</if>
		<if test="passWordDEF !=null and passWordDEF != '' ">and password =#{passWordDEF}</if>
	</where>
</select> 
以上基於JDK1.8