bug:
//原因:org.apache.ibatis.executor.ExecutorException:无法确定将生成的键分配给哪个参数。
//请注意,当有多个参数时,“ keyProperty”必须包含参数名称(例如“ param.id”)。
//指定的键属性为[id],可用参数为[menuId,userId,param1,param2]
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 [menuId, userId, param1, param2]
相关代码:
<insert id="create" keyProperty="id" useGeneratedKeys="true" parameterType="com.nuc.entity.UserMenu">
insert into tb_user_menu(
user_id,
menu_id
)values(
#{userId},
#{menuId}
)
</insert>
public int create(@Param("userId") Integer userId,@Param("menuId") Integer menuId);
原因:
create方法中有两个参数,mybatis并不知道keyProperty = "id"
这个的id要赋值给哪个参数的属性,所以需改为:
<insert id="create" keyProperty="userId.id" useGeneratedKeys="true" parameterType="com.nuc.entity.UserMenu">
insert into tb_user_menu(
user_id,
menu_id
)values(
#{userId},
#{menuId}
)
</insert>
如果传参只有一个对象的参数,去使用对象名.属性的方式也会报错,一个参数时,只需要为keyProperty="id"
总结
useGeneratedKeys
的意思是向传入的Model赋值自增长id 。而keyProperty
表示将自增长id赋值给哪个字段。所以当传入两个参数时,会报如上错误;
可参照getAssignerForParamMap
源码:
private Entry<String, KeyAssigner> getAssignerForParamMap(Configuration config, ResultSetMetaData rsmd,
int columnPosition, Map<String, ?> paramMap, String keyProperty, String[] keyProperties, boolean omitParamName) {
//判断paramMap是否只有一个唯一key
boolean singleParam = paramMap.values().stream().distinct().count() == 1;
//获取keyProperty的.的位置
int firstDot = keyProperty.indexOf('.');
//如果是多个参数,但是keyProperty又不包含.,会抛出错误
if (firstDot == -1) {
if (singleParam) {
return getAssignerForSingleParam(config, rsmd, columnPosition, paramMap, keyProperty, omitParamName);
}
throw new 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 " + ArrayUtil.toString(keyProperties) + " and available parameters are "
+ paramMap.keySet());
}
//多参数,需要截取keyProperty的.之前部分,去paramMap拿对应值
String paramName = keyProperty.substring(0, firstDot);
if (paramMap.containsKey(paramName)) {
String argParamName = omitParamName ? null : paramName;
String argKeyProperty = keyProperty.substring(firstDot + 1);
return entry(paramName, new KeyAssigner(config, rsmd, columnPosition, argParamName, argKeyProperty));
} else if (singleParam) {
return getAssignerForSingleParam(config, rsmd, columnPosition, paramMap, keyProperty, omitParamName);
} else {
throw new ExecutorException("Could not find parameter '" + paramName + "'. "
+ "Note that when there are multiple parameters, 'keyProperty' must include the parameter name (e.g. 'param.id'). "
+ "Specified key properties are " + ArrayUtil.toString(keyProperties) + " and available parameters are "
+ paramMap.keySet());
}
}