我想使用QueryRunner来执行ArrayList的插入。我在网上找到的唯一信息是插入一个Object []。有点像:
qr.update("insert into MyTable (param1,param2,param3) values (?,?,?)",
new Object[] { str1, str2, str3});
我显然希望避免循环遍历整个ArrayList并一次插入一个索引,因为每次要插入的行数都是未知的。
我只是想知道是否有人这样做过。查询返回一个List,所以我不明白为什么我不能插入List。任何建议表示赞赏。感谢。
答案 0 :(得分:7)
我知道这已经过时了,但我正在寻找有关Apache Commons DBUtils QueryRunner的信息并且遇到了这个......为了将来参考,您可以:
首先将ArrayList转换为Object [] []:
Object[][] params = null;
params = listOfObjectArrays.toArray(params);
然后将params
传递给QueryRunner上的批处理方法(返回int []):
qr.batch("insert into MyTable (param1,param2,param3) values (?,?,?)", params);
答案 1 :(得分:2)
我也在努力解决这个问题,但决定创建一个modelToSqlConverter。它不是我写过的最漂亮的代码,但它就像一个魅力。
我实际上在Dbutils周围创建了一个小包装器,我调用了GenericDataAccessor。它是一项正在进行中的工作,我会在我得到时间后立即将它放在github上。它对于所有中等规模的项目来说都是一个很棒的工具,对于像Hibernate这样的真正的ORM而言感觉很小,但是对于仅仅使用JDBC来说它很重要。怎么样。如果你愿意,可以随意使用它,它帮助了我很多。
这是ModelConverter
/**
* The <code>ModelToSqlConverter</code> class <br>
* <br>
* Deserializes the model and creates the sql string for update and insert.<br>
* Also generates the object array for the values from the model.
*/
public class ModelToSqlConverter{
private Object model;
private List<Object> params, keyParams, modelList;
private String fieldNameString, questionMarkString, sqlString, conditionString, updateString;
private boolean update;
private String[] keys;
private Object[][] multiParams;
/**
* Initializes a newly created <code>ModelToSqlConverter</code>
*
* @param model The model representing the ASW file.
* @param keys The keys for locating the right row in ASW file.
*/
@SuppressWarnings("unchecked")
private ModelToSqlConverter(Object model, String... keys){
this.model = model;
this.keys = keys;
params = new ArrayList<>();
keyParams = new ArrayList<>();
questionMarkString = "VALUES (";
fieldNameString = "(";
updateString = "";
conditionString = "WHERE ";
update = keys != null && keys.length > 0;
if(model instanceof List<?>){
modelList = (List<Object>) model;
convertModelListToSqlAndParams();
}else{
convertModelToSqlAndParams();
}
}
/**
* Main method for Converting Model into SQL String and to value parameters.
*/
private void convertModelToSqlAndParams(){
for(Field field : model.getClass().getDeclaredFields()){
try{
field.setAccessible(true);
Object value = field.get(model);
String fieldName = field.getName();
if(value != null && !fieldName.equalsIgnoreCase("serialVersionUID")){
if(!update){
addQuestionMark();
addNameToSql(fieldName);
addValueToObjectArray(value);
}else{
if(isKey(fieldName)){
conditionString += fieldName + " = ?,";
keyParams.add(value);
}else{
addParamAndNameToSql(fieldName);
addValueToObjectArray(value);
}
}
}
}catch(IllegalArgumentException e){
// TODO Auto-generated catch block
e.printStackTrace();
}catch(IllegalAccessException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
}
sqlString = update ? getUpdateSql() : getInsertSql();
for(Object key : keyParams){
addValueToObjectArray(key);
}
}
/**
* Main method for Converting Model into SQL String and to value parameters.
*/
private void convertModelListToSqlAndParams(){
int row = 0;
boolean isKey = false;
boolean firstModel = true;
Field[] fields = modelList.get(0).getClass().getDeclaredFields();
multiParams = new Object[modelList.size()][fields.length];
for(Object model : modelList){
int col = 0;
keyParams = new ArrayList<>();
for(Field field : fields){
try{
field.setAccessible(true);
Object value = field.get(model);
String fieldName = field.getName();
if(value != null && !fieldName.equalsIgnoreCase("serialVersionUID")){
if(!update){
if(firstModel){
addQuestionMark();
addNameToSql(fieldName);
}
addValueToMultiParams(value, row, col);
}else{
isKey = isKey(fieldName);
if(isKey){
if(firstModel){
conditionString += fieldName + " = ?,";
}
keyParams.add(value);
}else{
if(firstModel)
addParamAndNameToSql(fieldName);
addValueToMultiParams(value, row, col);
}
}
}
}catch(IllegalArgumentException e){
// TODO Auto-generated catch block
e.printStackTrace();
}catch(IllegalAccessException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
if(!isKey)
col++;
}
firstModel = false;
for(Object key : keyParams){
addValueToMultiParams(key, row, col);
col++;
}
row++;
}
sqlString = update ? getUpdateSql() : getInsertSql();
}
/**
* @param columnName
*/
private void addNameToSql(String columnName){
fieldNameString += columnName + ",";
}
/**
* @param value
*/
private void addValueToObjectArray(Object value){
params.add(value);
}
/**
* @param value
* @param row
* @param col
*/
private void addValueToMultiParams(Object value, int row, int col){
multiParams[row][col] = value;
}
public Object[][] getMultiValueParams(){
return removeNullsFromMultiArray(multiParams);
}
/**
* Adds question mark to string
*/
private void addQuestionMark(){
questionMarkString += "?,";
}
/**
* @param columnName
*/
private void addParamAndNameToSql(String columnName){
updateString += columnName + "= ?,";
}
/**
* @return the update SQL string.
*/
private String getUpdateSql(){
return updateString.substring(0, updateString.lastIndexOf(",")) + " " + conditionString.substring(0, conditionString.lastIndexOf(","));
}
/**
* @return the insert SQL string.
*/
private String getInsertSql(){
return fieldNameString.substring(0, fieldNameString.lastIndexOf(",")) + ") " + questionMarkString.substring(0, questionMarkString.lastIndexOf(","))
+ ")";
}
private Object[][] removeNullsFromMultiArray(Object[][] multiValuedArray){
for(int i = 0; i < multiValuedArray.length; i++){
ArrayList<Object> list = new ArrayList<Object>(); // creates a list to store the elements !=
// null
for(int j = 0; j < multiValuedArray[i].length; j++){
if(multiValuedArray[i][j] != null){
list.add(multiValuedArray[i][j]); // elements != null will be added to the list.
}
}
multiValuedArray[i] = list.toArray(new Object[list.size()]); // all elements from list to an
// array.
}
return multiValuedArray;
}
/**
* Checks if the field name is a key.
*
* @param fieldName
* @return true if the field is a key.
*/
private boolean isKey(String fieldName){
boolean isKey = false;
for(String key : keys){
if(fieldName.equalsIgnoreCase(key)){
isKey = true;
}
}
return isKey;
}
/**
* @return the params
*/
public Object[] getParams(){
return params.toArray();
}
/**
* @return the sqlString
*/
public String getSqlString(){
return sqlString;
}
/**
* @param params the params to set
*/
public void setParams(List<Object> params){
this.params = params;
}
/**
* @param sqlString the sqlString to set
*/
public void setSqlString(String sqlString){
this.sqlString = sqlString;
}
}
以下是您调用insert的方法。
/**
* Insert batch of rows from model list into the Database.
*
* @param modelsList List of model objects representing the Database table.
* @return int Array of inserted rows.
* @throws SQLException
*/
public <T> int[] insertWithListOfModels(List<T> modelsList) throws SQLException{
ModelToSqlConverter modelConverter = new ModelToSqlConverter(modelsList);
QueryRunner qryRunner = new QueryRunner();
int[] inserts = null;
System.out.println("INSERT INTO " + modelsList.get(0).getClass().getSimpleName().toUpperCase() + " " + modelConverter.getSqlString());
System.out.println(Arrays.deepToString(modelConverter.getMultiValueParams()));
inserts = qryRunner.batch(connection,
"INSERT INTO " + modelsList.get(0).getClass().getSimpleName().toUpperCase() + " " + modelConverter.getSqlString(),
modelConverter.getMultiValueParams());
return inserts;
}
它的工作方式是,您提交模型列表或仅提交单个对象。我提供的方法是用模型列表进行更新,但你明白了。 modelToSqlConvertor的构造函数处理所有内容。然后,使用dbutils qryRunner,您可以声明您的sql并从modelToSqlConverter调用getters来获取值和参数。
要完成此工作,您的模型必须与数据库表相同。我用JPA模仿了我的模特。
希望这有帮助!