sql中傳入一個list,返回一個list

-----------傳入數組------返回list<string>----------

String[] sendPersonIdArr = sendPersonId.split(",");
List<String> list = staffInfoService.ListPhonesByIds(sendPersonIdArr);


<!-- 經過userIds查詢員工的電話-->
	<select id="ListPhonesByIds" parameterType="String" resultType="String">
	 	SELECT h.telphone from hr_staff_info h left JOIN sys_user u on h.STAFFINFO_ID=u.STAFF_ID where 
 			u.id in  
 			<foreach collection="array" index="index" item="item" open="(" separator="," close=")">
				 #{item}
			</foreach>
	</select>

-----傳入List<string>----返回List<User>------
 
public List<User> findByUserIdList(List<String> userlist) throws Exception {
	return (List<User>) dao.findForList("UserMapper.findByUserIdList", userlist);
}

<!-- 經過userId的list來查詢userlist -->
	<select id="findByUserIdList" parameterType="java.util.List" resultMap="userResultMap" >
	select * from sys_user  where id in 
	 <foreach collection="list"  item="item" index="index" open="(" separator="," close=")">  
		 #{item}
	</foreach>
	</select>
-----------傳入一個map---------批量修改數據---------------

controller中:

Map<String, Object> map = new HashMap<>();
		map.put("notifyNum", notifyNum);
		map.put("userIdArr", userIdArr);
		userService.sendNotify(map);
		
sql中:

<!--發送通知,保存notifyNum 到user表中的notifyCodes中-->
<update id="sendNotify" parameterType="java.util.Map" >
	update user 
	set notify_codes=if(notify_codes is null or notify_codes='',#{notifyNum},CONCAT(notify_codes,',',#{notifyNum}))
	 where id in
        <foreach collection="userIdArr" index="index" item="item" open="(" separator="," close=")">
			  #{item}
       </foreach>
</update>		
		
總結:
①這裏傳入了一個String notifyNum和一個String[] userIdArr ,咱們只要在sql中名稱匹配就能夠了。
②批量修改也能夠用in 
③在修改的時候,咱們能夠在原來的字段值中直接後面追加字符串。當原來的值爲數字的時候,咱們能夠  update user set notify_codes=notify_codes+'2'  where id='24' 
這樣,假設原來爲5,那麼如今就爲 7 了。
當原來的值是一個String類型時,咱們能夠用 CONCAT(notify_codes,',',#{notifyNum}) 來在後面追加 。好比原來爲  "12" 如今最加一個  ",13"  那麼結果爲  "12,13"   
④判斷一個字段是否爲空的時候,用這樣用  if(notify_codes is null or notify_codes='','爲空或空字符串返回這個值','非空的時候返回這個值')  		

第二種方式:整條語句循環  (本身未驗證)java

<update id="batchUpdate"  parameterType="java.util.List">  
        
          <foreach collection="list" item="item" index="index" open="" close="" separator=";">  
                update test   
                <set>  
                  test=${item.test}+1  
                </set>  
                where id = ${item.id}  
         </foreach>  
            
    </update>



sql中咱們能夠傳入一個list或者一個數組,返回一個list。sql

這裏用到了sql中的 In,用到了sql中的遍歷。數組


在咱們要向mapper.xml中傳遞String參數的時候,須要sql中設置app

parameterType="String"

同時 要保證impl中的參數名和sql中的名字要一致。ide

以下:code

@Override
	public User findByUE(String userId)throws Exception{
		return (User)dao.findForObject("UserMapper.findById",userId);
	}
	
	sql :
	u.id = #{userId}
相關文章
相關標籤/搜索