Integer insertEntitySelectiveShard(@Param("tableSuffix") String tableSuffix,@Param("entity") XXXEntity entity);
<insert id="insertEntitySelectiveShard" parameterType="com.cnblogs.yjmyzz.dao.entity.XXXEntity" useGeneratedKeys="true" keyProperty="id">
可能有同學說了,按官網文檔的說法,keyProperty這裏寫法不規範:
![]()
既然是對象的屬性,正確的寫法應該是 keyProperty="entity.id",但該項目id生成方式,後來改用snowflake分佈式id算法,在insert前entity.id上已賦值了,也就無需mybatis在insert後自動返回,關鍵的是3.4.6版本,遇到這種不規範的寫法,並不會報錯,所以也就一直這樣跑着。
當升級到3.5.13後,運行報錯:
org.apache.ibatis.executor.ExecutorException: Error getting generated key or setting result to parameter object. Cause: org.apache.ibatis.executor.ExecutorException: Could not determine which parameter to assign generated keys to. Note that when there are multiple parameters, 'keyProperty' must include the parameter name (e.g. 'param.id'). Specified key properties are [id] and available parameters are [tableSuffix, param1, entity, param2]
經過實測,結論如下:
1、只有1個參數時,加不加@Param("entity") 都不會報錯
2、大於1個參數時,keyProperty必須寫成規範的entity.id,否則報錯
3、不管是幾個參數,keyColumn=“id" 始終不會報錯(也建議用該方式,前提是表上的主鍵字段名就是id)