import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Map; import javax.sql.DataSource; import org.apache.commons.dbcp.BasicDataSource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementCreator; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; public class TestRetrieveAutoGeneratedKeys { private static final String DRIVER_CLASSNAME = "oracle.jdbc.driver.OracleDriver"; private static final String IP = "192.168.123.72"; private static final int PORT = 1521; private static final String SID = "wmdw"; private static final String USERNAME = "dss"; private static final String PASSWORD = "dss"; private static final String INSERT_SQL = "insert into testid(id,name) values(test_SEQ.Nextval,?)"; /** * <pre> * @param args * </pre> */ public static void main(String[] args) { int count = 10000; TestRetrieveAutoGeneratedKeys test = new TestRetrieveAutoGeneratedKeys(); DataSource dataSource = createOracleDataSource(IP, PORT, SID, USERNAME, PASSWORD); JdbcTemplate jdbcTemplate = createJdbcTemplate(dataSource); for (int i = 0; i < count; i++) { Map<String, Object> map = test.getPKs(jdbcTemplate); System.out.println("id:" + Integer.valueOf(map.get("id").toString()).intValue()); } } /** * <pre> * 得到数据库自动生成的PK的id * 这里使用 oracle 数据库做的例子,其他的数据库同样适用,例如:MySQL,MS SQLServer * DB: Oracle database * -- Create table * create table testid( * id number(11), * name varchar2(100), * primary key(id) * ) * * -- Create sequence * create sequence test_SEQ * minvalue 1 * maxvalue 9999999999999999999999999999 * start with 1 * increment by 1 * nocache; * @return * </pre> */ private Map<String, Object> getPKs(JdbcTemplate jdbcTemplate) { KeyHolder keyHolder = createKeyHolder(); jdbcTemplate.update(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement( Connection connection) throws SQLException { PreparedStatement ps = connection.prepareStatement(INSERT_SQL, new int[] { 1 }); ps.setString(1, "name-1"); return ps; } }, keyHolder); return keyHolder.getKeys(); } private static DataSource createOracleDataSource(String ip, int port, String sid, String username, String password) { String url = "jdbc:oracle:thin:@" + ip + ":" + port + ":" + sid; BasicDataSource dataSource = createBasicDataSource(); dataSource.setDriverClassName(DRIVER_CLASSNAME); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); return dataSource; } private static BasicDataSource createBasicDataSource() { return new BasicDataSource(); } private static KeyHolder createKeyHolder() { return new GeneratedKeyHolder(); } private static JdbcTemplate createJdbcTemplate(DataSource dataSource) { return new JdbcTemplate(dataSource); } }
另外可以参考一下org.springframework.jdbc.core.simple.AbstractJdbcInsert.java的源代码,看见spring是如何写的。
部分内容如下:
/** * Method to execute the insert generating any number of keys */ private KeyHolder executeInsertAndReturnKeyHolderInternal(final List<Object> values) { if (logger.isDebugEnabled()) { logger.debug("The following parameters are used for call " + getInsertString() + " with: " + values); } final KeyHolder keyHolder = new GeneratedKeyHolder(); if (this.tableMetaDataContext.isGetGeneratedKeysSupported()) { getJdbcTemplate().update( new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection con) throws SQLException { PreparedStatement ps = prepareStatementForGeneratedKeys(con); setParameterValues(ps, values, getInsertTypes()); return ps; } }, keyHolder); } else { if (!this.tableMetaDataContext.isGetGeneratedKeysSimulated()) { throw new InvalidDataAccessResourceUsageException( "The getGeneratedKeys feature is not supported by this database"); } if (getGeneratedKeyNames().length < 1) { throw new InvalidDataAccessApiUsageException("Generated Key Name(s) not specified. " + "Using the generated keys features requires specifying the name(s) of the generated column(s)"); } if (getGeneratedKeyNames().length > 1) { throw new InvalidDataAccessApiUsageException( "Current database only supports retrieving the key for a single column. There are " + getGeneratedKeyNames().length + " columns specified: " + Arrays.asList(getGeneratedKeyNames())); } // This is a hack to be able to get the generated key from a database that doesn't support // get generated keys feature. HSQL is one, PostgreSQL is another. Postgres uses a RETURNING // clause while HSQL uses a second query that has to be executed with the same connection. final String keyQuery = this.tableMetaDataContext.getSimulationQueryForGetGeneratedKey( this.tableMetaDataContext.getTableName(), getGeneratedKeyNames()[0]); Assert.notNull(keyQuery, "Query for simulating get generated keys can't be null"); if (keyQuery.toUpperCase().startsWith("RETURNING")) { Long key = getJdbcTemplate().queryForObject(getInsertString() + " " + keyQuery, values.toArray(new Object[values.size()]), Long.class); Map<String, Object> keys = new HashMap<String, Object>(1); keys.put(getGeneratedKeyNames()[0], key); keyHolder.getKeyList().add(keys); } else { getJdbcTemplate().execute(new ConnectionCallback<Object>() { @Override public Object doInConnection(Connection con) throws SQLException, DataAccessException { // Do the insert PreparedStatement ps = null; try { ps = con.prepareStatement(getInsertString()); setParameterValues(ps, values, getInsertTypes()); ps.executeUpdate(); } finally { JdbcUtils.closeStatement(ps); } //Get the key Statement keyStmt = null; ResultSet rs = null; Map<String, Object> keys = new HashMap<String, Object>(1); try { keyStmt = con.createStatement(); rs = keyStmt.executeQuery(keyQuery); if (rs.next()) { long key = rs.getLong(1); keys.put(getGeneratedKeyNames()[0], key); keyHolder.getKeyList().add(keys); } } finally { JdbcUtils.closeResultSet(rs); JdbcUtils.closeStatement(keyStmt); } return null; } }); } return keyHolder; } return keyHolder; }
相关推荐
NULL 博文链接:https://huihai.iteye.com/blog/859622
标题“Spring-MVC+Spring-IOC+Spring-JdbcTemple”揭示了这个项目或教程是关于如何集成并使用Spring框架的三个核心模块:Spring MVC、Spring IOC(Inversion of Control,控制反转)以及Spring JDBC Template。...
标题 "spring+JdbcTemple+dbcp数据源的xml实现" 涉及到的是在Java环境中,使用Spring框架整合JDBC模板(JdbcTemplate)和Apache的DBCP数据库连接池来管理数据库连接的方式。这一组合是Java后端开发中常见的数据库...
标题“springboot-jpa加上jdbctemple”指的是在Spring Boot项目中同时使用JPA(Java Persistence API)和JdbcTemplate的技术整合。这是一个常见的后端开发场景,涉及到Spring Boot的数据库访问层的构建,旨在提供...
资源文件包含: commons-logging-1.2.jar , spring-beans-5.0.0.RELEASE.jar , spring-core-5.0.0.RELEASE.jar, spring-jdbc-5.0.0.RELEASE.jar spring-tx-5.0.0.RELEASE.jar
spring 中对大数据的处理,包括clob,blob的数据。比之jdbc下简便很多。
3、本项目适合计算机相关专业(人工智能、自动化、电子信息、物联网、通信工程、软件工程等)的在校学生、老师或者企业员工下载使用,也可作为毕业设计、课程设计、作业、项目初期立项演示等,当然也适合小白学习进阶...
PhoneShop-SSM:✦项目描述...配置spring.xml需要开启spring注解加载数据源注入jdbctemple配置拦截器3.编写业务流程:后台层次划分:控制层(control)服务层(service)数据库操作(dao)实体层(bean)工具类(tools)
Swing+Druid+jdbcTemple+jdk1.8 数据库: MySQL_5.6.46 开发工具:IDEA_2019.1.3 【使用说明】 导入结构和数据:sql/epms.sql 解压下载zip重命名EPMS-master文件夹为EPMS,IDEA打开该EPMS项目 修改配置数据库连接...