Spring中新建记录后返回自增主键的处理方法

接手一个旧系统改造的过程,要插入后立即返回自增值,不能重构guid类型主键,Spring提供了很优美的机制。

Spring利用GeneratedKeyHolder,提供了一个可以返回新增记录对应主键值的方法 :KeyHolder接口指代了一个通用的实现类GeneratedKeyHolder,该类返回新增记录时的自增长主键值

代码:

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import javax.sql.DataSource;

public class Main {

    public static void main(String[] args) {

        ApplicationContext context = new ClassPathXmlApplicationContext("TemporaryVenue-test.xml");
        DataSource dataSource = (DataSource)context.getBean("dataSource");
        JdbcTemplate  jdbcTemplate = new JdbcTemplate(dataSource);     
    
        String insert_sql = "insert into SYS_USERTV(username,password) values(?,?)";         
        
        //调用,获取插入后的自增值,其中"id"是自增字段名称
        System.out.println("方法调用获取当前自增int主键值" + insert(insert_sql,jdbcTemplate,"id"));
    
    }

    /**
     * 插入后返回自增主键值
     * @param jdbcTemplate
     * @return
     */
    private static Number insert(final String sql, 
            JdbcTemplate jdbcTemplate,
            final String keyName) {
       KeyHolder keyHolder = new GeneratedKeyHolder(); 
        int lines=jdbcTemplate.update(new PreparedStatementCreator() {
            
            @Override
            public PreparedStatement createPreparedStatement(Connection connection)
                    throws SQLException {
                PreparedStatement ps = PreStatement(sql, connection,keyName);
                return ps;
            }
        }, keyHolder);
            
            return keyHolder.getKey();
    }
    
    /**
     * 装载参数
     * @param sql
     * @param connection
     * @param keyName:自增字段名称
     * @return
     * @throws SQLException
     */
    private static PreparedStatement PreStatement(final String sql,
            Connection connection,String keyName) throws SQLException {
        PreparedStatement ps = connection.prepareStatement(sql,
                new String[] { keyName });
        ps.setString(1, new Date().toString());
        ps.setString(2, "aa");
        return ps;
    }

}

 

posted @ 2017-02-17 11:06  昕友软件开发  阅读(3322)  评论(0编辑  收藏  举报
欢迎访问我的开源项目:xyIM企业即时通讯