mybatis creates one or more new user insert fields and table names that are uncertain when adding the problem dynamically

  • 2020-06-12 09:15:30
  • OfStack

Create user:


/**
*  create 1 Two or more new users  insert  Field and table names are added dynamically when they are not specified 
*/
@Test
public void createAccount() {
  String lineColumn = "";
  Map<String, Object> paramsMap = new HashMap<String, Object>();
  Map<String, Object> dataMap = new HashMap<String, Object>();
  // map the key The value is a field, value For the need to insert  The user's value. 1 a map That is 1 A new user 
  List<Map<String, Object>> lineList = new ArrayList<Map<String, Object>>();
  dataMap.put("name", " Fish more ");
  dataMap.put("password", "123456");
  dataMap.put("gender", " female ");
  dataMap.put("id_no", "14");
  lineList.add(dataMap);
  //  In order to make the fields and values() I'm going to go through all of the values map the key, Build dynamic fields. 
  //  Accordingly, in accountMapper.xml I'm going to go through it lineList , and then iterate through it map the value, build insert  The value of the 
  for (String key : dataMap.keySet()) {
    lineColumn += key + ",";
  }
  // id It's not automatically incrementing, plus id field 
  //  Accordingly, in accountMapper.xml In the   In sequence nextval generate id
  lineColumn += "id";
  paramsMap.put("lineColumn", lineColumn);
  paramsMap.put("table", "account");
  paramsMap.put("lineList", lineList);
  if (accountMapper.createAccount(paramsMap) > 0) {
    System.out.println(" Creating a successful ");
  }
}

accountMapper. xml inserts sql for 1 new user (using the Oracle database)


<insert id="createAccount" parameterType="java.util.Map">
  INSERT INTO ${table}(${lineColumn}) select result.*,seq.nextval id from(
      <foreach collection="lineList" item="item" index="index" separator="union all">
      (select
        <foreach collection="item" index="key" item="_value" separator=","> #{_value}
        </foreach>
      from dual)
     </foreach>
  ) result
</insert>

Related articles: