读书人

ibatis insert 返回null有关问题

发布时间: 2012-11-10 10:48:51 作者: rapoo

ibatis insert 返回null问题

? ?

关于com.ibatis.sqlmap.client.SqlMapExecutor下 的insert (java.lang.String id, java.lang.Object parameterObject) 方法:

?

?

它的意思是说返回值是新插入记录的主键,类型为Object主要是因为主键类型可以是int也可以是String类型。

然而,如果我们使用下列的配置文件进行插入的话,返回的值为null

  1. <insert id="insertPrdcategory" parameterClass="Prdcategory">
  2. insert into Prdcategory ( name,pid,deep ) values ( #name#,
  3. #pid#, #deep# )
  4. </insert>

那我们要怎样解决这个问题,让它返回插入行的主键呢,这时我们就是使用到<selectKey>,下面仅以MSSQL数据库为例,改写 上述配置文件,具体如下:

  1. <insert id="insertPrdcategory" parameterClass="Prdcategory">
  2. insert into Prdcategory ( name,pid,deep ) values ( #name#,
  3. #pid#, #deep# )
  4. <selectKey resultClass="int" keyProperty="id">
  5. select max(id) from Prdcategory
  6. </selectKey>
  7. </insert>

?

DAO的实现类方法里面就应该这样写了(注意整型转换用Integer类名)

  1. public int insertPrdcategory(Prdcategory product) throws Exception {
  2. return (Integer)IbatisUtil.getSqlMapper().insert("insertPrdcategory", product);
  3. }

?

?

读书人网 >编程

热点推荐