Mybatis註解開發批量插入

一.Mybatis註解開發批量插入

	/**
	* 	接口上註解Mapper,這個Mapper
	* 	import org.apache.ibatis.annotations.Mapper
	* 	import org.apache.ibatis.annotations.Param;
	*   import org.apache.ibatis.annotations.Select;
	*   import org.apache.ibatis.annotations.Update;
	*/
	@Mapper
	public interface ProcessFormDao {
		// 形如
		@Insert("sql代碼")
		@Select("sql代碼")
		@Update("sql代碼")
		@Delete("sql代碼")
		ResultObject methodName(T t,O o);

		// 示例
		@Select("SELECT * FROM process_form WHERE id = #{processForm.id}")
		ProcessForm findProcessFormById(@Param("processForm") ProcessForm processForm);	


		/**
		 * 批量插入
		 * INSERT INTO node_auth(`node_id`,`allow_edit`,`allow_refuse`,`allow_rule`,`creator`,`create_time`,`editor`,`edit_time`)
		 * VALUES (?,?,?,?,?,?,?,?),(?,?,?,?,?,?,?,?),(?,?,?,?,?,?,?,?);
		 */ 

		/**
		 * 批量插入 ("sql代碼") 
	     * <script></script>標籤包裹起來
	     * VALUES 後的<foreach collection = 'nodeAuthList' item = 'item' index = 'index' separator = ','> </foreach> 標籤 
	     *  collection='nodeAuthList' 表示是遍歷哪一個集合
	     *  item='item' 表示循環遍歷中當前遍歷內容,比如nodeAuthList集合中的某一條/個 數據/對象
	     *  index = 'index' 索引是什麼,以什麼爲索引,
	     *  separator = ',' 分隔符,集合中元素與元素之前的分隔符
	     * @param nodeAuthList list節點權限對象
	     * @return Integer 返回保存成功數
	     */
	    @Insert("<script>INSERT INTO node_auth(`node_id`,`allow_edit`,`allow_refuse`,`allow_rule`,`creator`,`create_time`,`editor`,`edit_time`) VALUES "
	            + " <foreach collection = 'nodeAuthList' item = 'item' index = 'index' separator = ','> "
	            + " (#{item.nodeId}, #{item.allowEdit}, #{item.allowRefuse}, #{item.allowRule}, #{item.creator},#{item.createTime},#{item.editor},#{item.editTime}) "
	            + " </foreach></script>")
	    Integer insertNodeAuth(@Param("nodeAuthList") List<NodeAuth> nodeAuthList);

		

}

使用

@RunWith(SpringRunner.class)
@SpringBootTest
public class ProcessDefinitionDaoTest extends TestCase {
		/**
	     * 注入dao
	     */
	    @Autowird
	    private NodeAuthDao nodeAuthDao;

		@Test
	    public void te4() {
	    	Integer integer = nodeAuthDao.insertNodeAuth(nodeAuthList);
	    	System.out.println("批量保存數: "+integer);
	    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章