ibatis
使用主键回填
的步骤
- 在
mapper文件
中,设置两个属性.
keyProperty
: 指定POJO
中主键的属性名称;
useGeneratedKeys
: 设置true
,使用数据库内部生成的主键;<insert id="auto_PK_test" keyProperty="id" useGeneratedKeys="true"> insert emp(name) value(#{name}) </insert>
- 取出
ibatis
主键回填的值.
sql语句
执行成功后,ibatis
会自动将数据库自动生成的主键值
赋值到对应的POJO
的主键属性上.SqlSession session = sql_session_factory.openSession(); Auto_PK_mapper dao = session.getMapper(Auto_PK_mapper.class); Emp obj = new Emp(); obj.setName("xiao_zhu"); boolean result = dao.auto_PK_test(obj); log.info(result); session.commit(); log.info(obj.getId());
- 校验输出信息部分截取.
DEBUG 2019-01-11 23:11:27,281 org.apache.ibatis.transaction.jdbc.JdbcTransaction : Opening JDBC Connection DEBUG 2019-01-11 23:11:27,559 org.apache.ibatis.datasource.pooled.PooledDataSource : Created connection 12394814. DEBUG 2019-01-11 23:11:27,563 org.apache.ibatis.transaction.jdbc.JdbcTransaction : Setting autocommit to false on JDBC Connection [ com.mysql.jdbc.JDBC4Connection@bd213e] DEBUG 2019-01-11 23:11:27,563 org.apache.ibatis.logging.jdbc.BaseJdbcLogger : ==> Preparing: insert emp(name) value(?) DEBUG 2019-01-11 23:11:27,606 org.apache.ibatis.logging.jdbc.BaseJdbcLogger : ==> Parameters: xiao_zhu(String) DEBUG 2019-01-11 23:11:27,610 org.apache.ibatis.logging.jdbc.BaseJdbcLogger : <== Updates: 1 INFO 2019-01-11 23:11:27,610 siye.ibatis.test.Auto_PK_test : true DEBUG 2019-01-11 23:11:27,610 org.apache.ibatis.transaction.jdbc.JdbcTransaction : Committing JDBC Connection [com.mysql.jdbc.JDBC4Connection@bd213e] INFO 2019-01-11 23:11:27,633 siye.ibatis.test.Auto_PK_test : 12