在mybatis的xml配置文件中,如果用自定义insert语句,需要注意如下两点:
1)如果要使用selectKey提前自动生成字段ID,就在mapper interface方法定义中,如果使用@param。就需要在使用insert语句中,通过@param指定的名称来方位bean的属性;如果不使用@param就可以省去名称。
下面是使用@param的写法(含mapper interface和xml):
下面是不使用@param的写法(含mapper interface和xml):
就这个例子来说,不使用@param会更简洁。
2)使用selectKey获取多列数据时,千万不要在keyProperty中的列之间加空格(一般处于编码习惯,都会自然而然的加一个空格)。如下图:
否则,会报错如下:
ERRORServlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.executor.ExecutorException: No setter found for the keyProperty ’ timestamp’ in com.huaguang.observ.model.ch.SpanSnapshot.] with root cause
org.apache.ibatis.executor.ExecutorException: No setter found for the keyProperty ’ timestamp’ in com.huaguang.observ.model.ch.SpanSnapshot.
at org.apache.ibatis.executor.keygen.SelectKeyGenerator.setValue(SelectKeyGenerator.java:117)
正确的写法,去掉空格,如下图:
然后代码就能够正常运行了。