[英]Using HashMap dynamically for parameter mapping in mybatis
好的,所以這是使用 ibatis 將 HashMap 值插入表這個問題的重新發布(但我正在尋找不同的方式 - 答案對我不起作用)。
DB1GetStudentDataMapper.xml (查詢一個數據庫)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.testing.db1.DB1GetStudentDataMapper">
<select id="selectAllStudents" resultType="java.util.Map">
SELECT STUDENT_CD, STUDENT_NM, PARENT_CD, CREATED_DATE
FROM STUDENT
WHERE STD_STATUS='ACT'
</select>
</mapper>
DB2InsertStudentMapper.xml (這個查詢到不同的數據庫)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.testing.db2.DB2InsertStudentMapper">
<insert id="insertStudent" parameterType="java.util.HashMap">
INSERT INTO STUDENT
<!-- dynamically select column names from hashmap -->
(#{stdMap.keySet}) // this is not working - its coming as null
<!-- dynamically select values for the above columns from hashmap -->
VALUES (#{stdMap.values}) // this is not working - its coming as null
</insert>
</mapper>
DB2InsertStudentMapper.java
public interface TMODSBDataRefreshMapper {
void insertStudent(@Param("stdMap") HashMap stdMap);
}
學生數據處理程序
public class Student {
// I have defaultExecutorType as BATCH in my mapper config file
private DB1GetStudentDataMapper db1Mapper; // Interface Mapper for first data source
private DB2InsertStudentMapper db2Mapper; // Interface Mapper for second data source
public processStudent() throws Exception {
List<HashMap> rs = db1Mapper.selectAllStudents(); // Gets some 15k+ records
for(int i =0; i < rs.size(); i++) { // so this will loop through 15k+ records
HashMap result = rs.get(i);
System.out.println(result.keySet()); // prints column names from select query [STUDENT_CD, STUDENT_NM, PARENT_CD, CREATED_DATE]
System.out.println(result.values()); // prints above column values of first data set [1001, Mike, 5001, 2021-07-01]
// All I am trying is to insert above 15k records into different database dynamically rather than creating POJO
db2Mapper.insertStudent(result);
}
}
}
注意:例如,我使用了 4 列 - 我有大約 150 多列可以使用..
PS:請記住,當您使用較少的列時,此解決方案效果更好 - 但如果您有批量插入,則效果不佳 - 它會影響性能。
使用<foreach />
迭代映射時,鍵和值分別分配給index
和item
指定的變量。
所以,你的插入語句應該是這樣的。
<insert id="insertStudent">
INSERT INTO STUDENT (
<foreach collection="stdMap" index="col" separator=",">
${col}
</foreach>
) VALUES (
<foreach collection="stdMap" item="val" separator=",">
#{val}
</foreach>
)
</insert>
${}
作為列名,並使用#{}
作為值。 有關詳細信息,請參閱常見問題解答。java.util.LinkedHashMap
作為<select />
的結果類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.