title: get auto-genearated key for the inserted record in mybatis
body: <p>I am working under a web application which use spring mvc + mybatis + mysql.</p>
  
  <p>And I found that I can not get the auto-generated key for the last inserted record (I have googled so much).</p>
  
  <p>This is the related configuration(take the model 'Post' for example):</p>
  
  <h3>spring.xml:</h3>
  
  <pre class="lang-xml prettyprint-override"><code>&lt;bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"&gt;
      //omitted
  &lt;/bean&gt;
  
  &lt;bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"&gt;
      &lt;property name="dataSource" ref="dataSource" /&gt;
      &lt;property name="configLocation" value="config.xml" /&gt;
  &lt;/bean&gt;
  
  &lt;bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"&gt;
      &lt;constructor-arg index="0" ref="sqlSessionFactory" /&gt;
  &lt;/bean&gt;
  </code></pre>
  
  <h3>mybatis config.xml</h3>
  
  <pre><code>&lt;configuration&gt;
      &lt;typeAliases&gt;
          &lt;typeAlias alias="Post" type="com.king.model.Post" /&gt;
      &lt;/typeAliases&gt;
      &lt;mappers&gt;
          &lt;mapper resource="com/king/model/PostMapper.xml" /&gt;
      &lt;/mappers&gt;
  &lt;/configuration&gt;
  </code></pre>
  
  <h3>PostMapper.xml:</h3>
  
  <pre><code>&lt;mapper namespace="com.king.model.PostMapper"&gt;
      &lt;insert id="insert" parameterType="Post"&gt;
          insert into posts (title,body,created_at,updated_at) values (#{title},#{body},#{createDate},#{updateDate})
      &lt;/insert&gt;
  &lt;/mapper&gt;
  </code></pre>
  
  <h3>Dao:</h3>
  
  <pre class="lang-java prettyprint-override"><code>public abstract class AbstractSimpleDaoImpl&lt;T&gt; extends SqlSessionDaoSupport{
      @Override
      public int add(T entity) {
          return getSqlSession().insert(getMapperNamespace() + ".insert", entity);
      }
  
      protected abstract String getMapperNamespace();
  }
  
  public class PostDao extends AbstractSimpleDaoImpl&lt;Post&gt; {
      @Override
      protected String getMapperNamespace() {
          return "com.king.model.PostMapper";
      }
  }
  </code></pre>
  
  <hr>
  
  <p>However,when I insert a new Post to database:</p>
  
  <pre class="lang-java prettyprint-override"><code>postDao.add(post);
  </code></pre>
  
  <p>I can not get the generated id for the inserted post. I always get 1. I know this is the row-affected number.</p>
  
  <p>Also,I read the mybatis guide,and I tried this:</p>
  
  <pre class="lang-xml prettyprint-override"><code>&lt;insert id="insert" parameterType="Post" useGeneratedKeys="true" keyProperty="id"&gt;
  </code></pre>
  
  <p>But it seems that,this does not work.</p>
  
  <p>How to fix it?</p>