昨天在做项目的时候遇到了一个坑,没错,就是获取MyBatis自增长主键值的坑。因为之前一直用ibatis,所以惯性的用了ibatis的写法,结果返回的值一直是1(受影响的行数)。于是去翻了翻MyBatis的源码,发现它把主键值放到了参数对象上,获取主键值需要用参数对象去get主键值。真是坑。我先把解决办法放出来,然后再接着分析MyBatis的源码是怎么做的。
CREATE TABLE `user` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`user_name` VARCHAR(32) NULL DEFAULT NULL,
`pass_word` VARCHAR(16) NULL DEFAULT NULL,
`address` VARCHAR(16) NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
;
public class UserScope implements Serializable{
/**
* 姓名
*/
private String userName;
/**
* 主键ID
*/
private Integer id;
/**
* 密码
*/
private String passWord;
/**
* 地址
*/
private String address;
}
省略getter、setter。
@Override
public void addUser(UserScope userScope) {
this.getSqlSession().insert("userMapper.addUser",userScope);
}
@Override
public int addUserSelectKey(UserScope userScope){
this.getSqlSession().insert("userMapper.insertSelectKey",userScope);
System.out.println(userScope);
return userScope.getId();//获取自增长主键值
}
insert user(user_name,pass_word,address) values (#{userName},#{passWord},#{address})
select LAST_INSERT_ID()
insert user(user_name,pass_word,address) values (#{userName},#{passWord},#{address})
@Override
public int update(String statement, Object parameter) {
try {
dirty = true;
//这里是根据命名空间和ID获取要执行的sql的信息
MappedStatement ms = configuration.getMappedStatement(statement);
return executor.update(ms, wrapCollection(parameter));//执行sql
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error updating database. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}
@Override
public int update(MappedStatement ms, Object parameter) throws SQLException {
ErrorContext.instance().resource(ms.getResource()).activity("executing an update").object(ms.getId());//记录操作信息,如果有异常的话,会从这里取异常信息
if (closed) {
throw new ExecutorException("Executor was closed.");
}
clearLocalCache();//清空本地缓存
return doUpdate(ms, parameter);//执行sql
}
public int doUpdate(MappedStatement ms, Object parameter) throws SQLException {
Statement stmt = null;
try {
Configuration configuration = ms.getConfiguration();
StatementHandler handler = configuration.newStatementHandler(this, ms, parameter, RowBounds.DEFAULT, null, null);//获取执行sql的Statement
stmt = prepareStatement(handler, ms.getStatementLog());//封装StatementHandler的信息。打开连接、事务是否超时等。
return handler.update(stmt);//执行sql
} finally {
closeStatement(stmt);
}
}
public int update(Statement statement) throws SQLException {
PreparedStatement ps = (PreparedStatement) statement;
ps.execute();//这里是调用的JDBC4PreparedStatement执行sql
int rows = ps.getUpdateCount();//获取受影响的行数,也就是调用插入操作的时候返回的真正值。
Object parameterObject = boundSql.getParameterObject();//获取参数对象
KeyGenerator keyGenerator = mappedStatement.getKeyGenerator();//判断是那种KeyGenerator
keyGenerator.processAfter(executor, mappedStatement, ps, parameterObject);//根据KeyGenerator去set主键值
return rows;
}
public void processBatch(MappedStatement ms, Statement stmt, Collection
private void populateKeys(ResultSet rs, MetaObject metaParam, String[] keyProperties, TypeHandler>[] typeHandlers) throws SQLException {
for (int i = 0; i < keyProperties.length; i++) {
TypeHandler> th = typeHandlers[i];
if (th != null) {
Object value = th.getResult(rs, i + 1);
metaParam.setValue(keyProperties[i], value);//在参数对象中设置keyProperty的字段值
}
}
}
public void setValue(String name, Object value) {
PropertyTokenizer prop = new PropertyTokenizer(name);
if (prop.hasNext()) {
MetaObject metaValue = metaObjectForProperty(prop.getIndexedName());
if (metaValue == SystemMetaObject.NULL_META_OBJECT) {
if (value == null && prop.getChildren() != null) {
// don't instantiate child path if value is null
return;
} else {
metaValue = objectWrapper.instantiatePropertyValue(name, prop, objectFactory);
}
}
metaValue.setValue(prop.getChildren(), value);
} else {
objectWrapper.set(prop, value);//在参数对象中设置keyProperty的字段值(根据反射来操作的)
}
}
上面的objectWrapper为BeanWrapper,我们直接进入到BeanWrapper中。
private void setBeanProperty(PropertyTokenizer prop, Object object, Object value) {
try {
Invoker method = metaClass.getSetInvoker(prop.getName());
Object[] params = {value};
try {
method.invoke(object, params);//设置参数对象的值
}
这里的method为SetFieldInvoker。invoke的方法代码如下:
public Object invoke(Object target, Object[] args) throws IllegalAccessException, InvocationTargetException {
field.set(target, args[0]);//这个field对象就是java.lang.reflect.Field对象。
return null;
}
Invoker的类图如下:
public void addUserBatch(List list) {
this.getSqlSession().insert("userMapper.addUserBatch",list);
System.out.println(Arrays.toString(list.toArray()));
}
insert user(user_name,pass_word,address) values
( #{item.userName},#{item.passWord},#{item.address} )
主键值已经设置到了list集合的对象中了,获取方法和普通插入的获取方式一样。