創建用戶:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
/** * 創建一個或多個新用戶 insert 字段和表名不確定時動態添加 */ @Test public void createAccount() { String lineColumn = "" ; Map<String, Object> paramsMap = new HashMap<String, Object>(); Map<String, Object> dataMap = new HashMap<String, Object>(); // map的key值為字段,value為需要insert 用戶的值。一個map即是一個新用戶 List<Map<String, Object>> lineList = new ArrayList<Map<String, Object>>(); dataMap.put( "name" , "魚多" ); dataMap.put( "password" , "123456" ); dataMap.put( "gender" , "女" ); dataMap.put( "id_no" , "14" ); lineList.add(dataMap); // 為了使字段和values()里面的值對應起來,遍歷出map的key,構建出動態字段。 // 相應的,在accountMapper.xml中用遍歷出lineList,然后遍歷map的value,構建出insert 的值 for (String key : dataMap.keySet()) { lineColumn += key + "," ; } // id不會自動遞增,加上id字段 // 相應的,在accountMapper.xml中 用序列的nextval生成id lineColumn += "id" ; paramsMap.put( "lineColumn" , lineColumn); paramsMap.put( "table" , "account" ); paramsMap.put( "lineList" , lineList); if (accountMapper.createAccount(paramsMap) > 0 ) { System.out.println( "創建成功" ); } } |
accountMapper.xml插入一個新用戶的sql(使用Oracle數據庫)
1
2
3
4
5
6
7
8
9
10
|
<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> |
以上所述是小編給大家介紹的mybatis創建一個或多個新用戶 insert 字段和表名不確定時動態添加問題,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:http://blog.csdn.net/laowangwsy/article/details/56274757