創(chuàng)建用戶:
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
|
/** * 創(chuàng)建一個(gè)或多個(gè)新用戶 insert 字段和表名不確定時(shí)動(dòng)態(tài)添加 */ @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 用戶的值。一個(gè)map即是一個(gè)新用戶 List<Map<String, Object>> lineList = new ArrayList<Map<String, Object>>(); dataMap.put( "name" , "魚(yú)多" ); dataMap.put( "password" , "123456" ); dataMap.put( "gender" , "女" ); dataMap.put( "id_no" , "14" ); lineList.add(dataMap); // 為了使字段和values()里面的值對(duì)應(yīng)起來(lái),遍歷出map的key,構(gòu)建出動(dòng)態(tài)字段。 // 相應(yīng)的,在accountMapper.xml中用遍歷出lineList,然后遍歷map的value,構(gòu)建出insert 的值 for (String key : dataMap.keySet()) { lineColumn += key + "," ; } // id不會(huì)自動(dòng)遞增,加上id字段 // 相應(yīng)的,在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( "創(chuàng)建成功" ); } } |
accountMapper.xml插入一個(gè)新用戶的sql(使用Oracle數(shù)據(jù)庫(kù))
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創(chuàng)建一個(gè)或多個(gè)新用戶 insert 字段和表名不確定時(shí)動(dòng)態(tài)添加問(wèn)題,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)服務(wù)器之家網(wǎng)站的支持!
原文鏈接:http://blog.csdn.net/laowangwsy/article/details/56274757