MyBatis-主键回填

ibatis使用主键回填的步骤

  1. mapper文件中,设置两个属性.
    keyProperty : 指定POJO中主键的属性名称;
    useGeneratedKeys : 设置true,使用数据库内部生成的主键;
    <insert id="auto_PK_test" keyProperty="id" 
    	useGeneratedKeys="true">               
    	insert emp(name) value(#{name})        
    insert>                                                                      
    
  2. 取出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());
    
  3. 校验输出信息部分截取.
    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
    

你可能感兴趣的:(归档弃用)