SelectKey在Mybatis中是为了解决Insert数据时不支持主键自动生成的问题,他能够很随意的设置生成主键的方式。html
无论SelectKey有多好,尽可能不要遇到这种状况吧,毕竟很麻烦。java
selectKey Attributesmysql
属性
描述sql
keyProperty
selectKey 语句结果应该被设置的目标属性。数据库
resultType
结果的类型。MyBatis 一般能够算出来,可是写上也没有问题。MyBatis 容许任何简单类型用做主键的类型,包括字符串。apache
order
这能够被设置为 BEFORE 或 AFTER。若是设置为 BEFORE,那么它会首先选择主键,设置 keyProperty 而后执行插入语句。若是设置为 AFTER,那么先执行插入语句,而后是 selectKey 元素-这和如 Oracle 数据库类似,能够在插入语句中嵌入序列调用。app
statementType
和前面的相 同,MyBatis 支持 STATEMENT ,PREPARED 和CALLABLE 语句的映射类型,分别表明 PreparedStatement 和CallableStatement 类型。ide
SelectKey须要注意order属性,像Mysql一类支持自动增加类型的数据库中,order须要设置为after才会取到正确的值。函数
像Oracle这样取序列的状况,须要设置为before,不然会报错。this
另外在用Spring管理事务时,SelectKey和插入在同一事务当中,于是Mysql这样的状况因为数据未插入到数据库中,因此是得不到自动增加的Key。取消事务管理就不会有问题。
下面是一个xml和注解的例子,SelectKey很简单,两个例子就够了:
[html] view plaincopy

- <insert id="insert" parameterType="map">
- insert into table1 (name) values (#{name})
- <selectKey resultType="java.lang.Integer" keyProperty="id">
- CALL IDENTITY()
- </selectKey>
- </insert>
上面xml的传入参数是map,selectKey会将结果放到入参数map中。用POJO的状况同样,可是有一点须要注意的是,keyProperty对应的字段在POJO中必须有相应的setter方法,setter的参数类型还要一致,不然会报错。
[java] view plaincopy

- @Insert("insert into table2 (name) values(#{name})")
- @SelectKey(statement="call identity()", keyProperty="nameId", before=false, resultType=int.class)
- int insertTable2(Name name);
上面是注解的形式。
在insert语句中,在Oracle常常使用序列、在MySQL中使用函数来自动生成插入表的主键,并且须要方法能返回这个生成主键。使用myBatis的selectKey标签能够实现这个效果。
下面例子,使用mysql数据库自定义函数nextval('student'),用来生成一个key,并把他设置到传入的实体类中的studentId属性上。因此在执行完此方法后,边能够经过这个实体类获取生成的key。
Xml代码 
- <!-- 插入学生 自动主键-->
- <insert id="createStudentAutoKey" parameterType="liming.student.manager.data.model.StudentEntity" keyProperty="studentId">
- <selectKey keyProperty="studentId" resultType="String" order="BEFORE">
- select nextval('student')
- </selectKey>
- INSERT INTO STUDENT_TBL(STUDENT_ID,
- STUDENT_NAME,
- STUDENT_SEX,
- STUDENT_BIRTHDAY,
- STUDENT_PHOTO,
- CLASS_ID,
- PLACE_ID)
- VALUES (#{studentId},
- #{studentName},
- #{studentSex},
- #{studentBirthday},
- #{studentPhoto, javaType=byte[], jdbcType=BLOB, typeHandler=org.apache.ibatis.type.BlobTypeHandler},
- #{classId},
- #{placeId})
- </insert>
调用接口方法,和获取自动生成key
Java代码 
- StudentEntity entity = new StudentEntity();
- entity.setStudentName("黎明你好");
- entity.setStudentSex(1);
- entity.setStudentBirthday(DateUtil.parse("1985-05-28"));
- entity.setClassId("20000001");
- entity.setPlaceId("70000001");
- this.dynamicSqlMapper.createStudentAutoKey(entity);
- System.out.println("新增学生ID: " + entity.getStudentId());