mybatis之接口方法多参数的三种实现方式

 关键代码举例:

DaoMapper.xml

 1     <!-- 传入多个参数时,自动转换为map形式 -->
 2     <insert id="insertByColumns" useGeneratedKeys="true" keyProperty="id">
 3         insert into user (id, name, age) values (NULL ,#{param1}, #{param2})
 4     </insert>
 5     <insert id="insertByZhuJie" useGeneratedKeys="true" keyProperty="id">
 6         insert into user (id, name, age) values (NULL ,#{name}, #{age})
 7     </insert>
 8     <insert id="insertByMap" useGeneratedKeys="true" keyProperty="id">
 9         insert into user (id, name, age) values (NULL ,#{name}, #{age})
10     </insert>

 

UserDao.java

1     // 插入数据;多参数三种方式:默认Map、使用Map传参和使用注解别名
2     public int insertByColumns(String name, int age);
3     public int insertByZhuJie(@Param("name") String name, @Param("age") int age);
4     public int insertByMap(Map map);

 

TestDao.java

 1     //   多参数插入数据的三种方式
 2     @Test
 3     public void testInsertByColumns() {
 4         UserDao userDao = session.getMapper(UserDao.class);
 5         String name = "insertByColumns";
 6         int age = 33;
 7 //        int n = userDao.insertByColumns(name, age);
 8 //        int n = userDao.insertByZhuJie(name, age);
 9 
10         Map map = new HashMap();
11         map.put("name", name);
12         map.put("age", age);
13         int n = userDao.insertByMap(map);
14 
15         session.commit();
16         System.out.println("插入数据name:" + name);
17         System.out.println(n);
18     }

 

posted @ 2018-01-15 15:18  星瑞  阅读(413)  评论(0编辑  收藏  举报