用GeneratedKeyHolder获得新建数据主键值

Spring提供了一个可以返回新增记录对应主键值的方法: 
int update(PreparedStatementCreator psc, KeyHolder generatedKeyHolder)

Spring为KeyHolder接口指代了一个通用的实现类GeneratedKeyHolder,该类返回新增记录时的自增长主键值。
如:新增用户对象后,希望将主键值加载到对象中: 

public  User  createUser ( final  User  user )  {
         final  String  sql  =  "insert into sys_users(username, password, salt, locked) values(?,?,?, ?)" ;
         GeneratedKeyHolder  keyHolder  =  new  GeneratedKeyHolder ( ) ;
         jdbcTemplate . update ( new  PreparedStatementCreator ( )  {
              public  PreparedStatement  createPreparedStatement ( Connection  connection )  throws  SQLException  {
                   PreparedStatement  psst  =  connection . prepareStatement ( sql ,  new  String [ ]  {  "id"  }) ;
                   psst . setString ( 1 ,  user . getUsername ( )) ;
                   psst . setString ( 2 ,  user . getPassword ( )) ;
                   psst . setString ( 3 ,  user . getSalt ( )) ;
                   psst . setBoolean ( 4 ,  user . getLocked ( )) ;
                   return  psst ;
              }
         } ,  keyHolder ) ;
         user . setId ( keyHolder . getKey ( ) . longValue ( )) ;
         return  user ;
     }




你可能感兴趣的:(用GeneratedKeyHolder获得新建数据主键值)