List of usage examples for java.sql Statement RETURN_GENERATED_KEYS
int RETURN_GENERATED_KEYS
To view the source code for java.sql Statement RETURN_GENERATED_KEYS.
Click Source Link
From source file:com.bluecollarcoder.dao.RecipeRepository.java
public void persist(final Recipe recipe) { KeyHolder key = new GeneratedKeyHolder(); jdbc.update((Connection con) -> { PreparedStatement stmt = con.prepareStatement( "insert into recipes (recipe_name, recipe_url, recipe_photo) values (?, ?, ?)", Statement.RETURN_GENERATED_KEYS); stmt.setString(1, recipe.getTitle()); stmt.setString(2, recipe.getUrl()); stmt.setString(3, recipe.getPhotoUrl()); return stmt; }, key);// w ww . jav a2 s. co m Number recipeId = (Number) key.getKeys().get("recipe_id"); for (String name : recipe.getIngredients().keySet()) { key = new GeneratedKeyHolder(); jdbc.update((Connection con) -> { PreparedStatement stmt = con.prepareStatement( "insert into ingredients (ingredient_name) values (?)", Statement.RETURN_GENERATED_KEYS); stmt.setString(1, name); return stmt; }, key); Number ingredientId = (Number) key.getKeys().get("ingredient_id"); String amount = recipe.getIngredients().get(name); jdbc.update("insert into ingredient_amount (recipe_id, ingredient_id, amount) values (?, ?, ?)", new Object[] { recipeId, ingredientId, amount }, new int[] { Types.INTEGER, Types.INTEGER, Types.VARCHAR }); } }
From source file:org.mskcc.cbio.portal.dao.DaoCopyNumberSegmentFile.java
public static int addCopyNumberSegmentFile(CopyNumberSegmentFile copySegFile) throws DaoException { Connection con = null;/*w w w . ja v a 2s . co m*/ PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoCopyNumberSegmentFile.class); pstmt = con.prepareStatement( "INSERT INTO copy_number_seg_file (`CANCER_STUDY_ID`, `REFERENCE_GENOME_ID`, `DESCRIPTION`,`FILENAME`)" + " VALUES (?,?,?,?)", Statement.RETURN_GENERATED_KEYS); pstmt.setInt(1, copySegFile.cancerStudyId); pstmt.setString(2, copySegFile.referenceGenomeId.toString()); pstmt.setString(3, copySegFile.description); pstmt.setString(4, copySegFile.filename); pstmt.executeUpdate(); rs = pstmt.getGeneratedKeys(); if (rs.next()) { return rs.getInt(1); } return -1; } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoCopyNumberSegment.class, con, pstmt, rs); } }
From source file:com.job.portal.utils.AbstractDAO.java
public int insert(String query, Object[] values) throws SQLException { int id = -1;/*from w w w . ja v a 2 s.c om*/ Object o = null; String type = null; Date d = null; java.util.Date utilDate = null; if (con.isClosed()) { con = new DbConnection().getConnection(); } ps = con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); for (int i = 0; i < values.length; i++) { o = values[i]; type = o.getClass().toString(); if (type.contains("String")) { ps.setString(i + 1, (String) o); } else if (type.contains("Integer")) { ps.setInt(i + 1, (Integer) o); } else if (type.contains("Long")) { ps.setLong(i + 1, (Long) o); } else if (type.contains("Date")) { utilDate = (java.util.Date) o; ps.setDate(i + 1, new Date(utilDate.getTime())); } } id = ps.executeUpdate(); closeConnections(); return id; }
From source file:com.dangdang.ddframe.rdb.sharding.spring.AutoIncrementDBUnitTest.java
@Test public void test() throws SQLException { try (Connection connection = getShardingDataSource().getConnection(); Statement statement = connection.createStatement()) { statement.execute("INSERT INTO `t_order` (`user_id`, `status`) VALUES (1, 'init')", Statement.RETURN_GENERATED_KEYS); assertTrue(statement.getGeneratedKeys().next()); assertEquals(statement.getGeneratedKeys().getLong(1), 101L); statement.execute(//from ww w .j a va2 s. co m "INSERT INTO `t_order_item` (`order_id`, `user_id`, `status`) VALUES (101, 1, 'init')", Statement.RETURN_GENERATED_KEYS); assertTrue(statement.getGeneratedKeys().next()); assertEquals(statement.getGeneratedKeys().getLong(1), 99L); } }
From source file:com.apress.prospringintegration.springenterprise.stocks.dao.jdbc.PSStockCreater.java
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { String sql = "INSERT INTO " + "STOCKS (SYMBOL, INVENTORY_CODE, PRICE_PER_SHARE," + "QUANTITY_AVAILABLE, EXCHANGE_ID, PURCHASE_DATE) " + "VALUES (?, ?, ?, ?, ?, ?)"; PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); ps.setString(1, stock.getSymbol());//from ww w. j a va 2 s. c om ps.setString(2, stock.getInventoryCode()); ps.setFloat(3, stock.getSharePrice()); ps.setFloat(4, stock.getQuantityAvailable()); ps.setString(5, stock.getExchangeId()); ps.setDate(6, new java.sql.Date(stock.getPurchaseDate().getTime())); return ps; }
From source file:com.javacreed.examples.spring.ExampleDao.java
public long addNew(final String name) { final PreparedStatementCreator psc = new PreparedStatementCreator() { @Override/*ww w . j a v a2 s . c o m*/ public PreparedStatement createPreparedStatement(final Connection connection) throws SQLException { final PreparedStatement ps = connection.prepareStatement("INSERT INTO `names` (`name`) VALUES (?)", Statement.RETURN_GENERATED_KEYS); ps.setString(1, name); return ps; } }; // The newly generated key will be saved in this object final KeyHolder holder = new GeneratedKeyHolder(); jdbcTemplate.update(psc, holder); final long newNameId = holder.getKey().longValue(); return newNameId; }
From source file:mx.com.pixup.portal.dao.FormaPagoDaoJdbc.java
@Override public FormaPago insertFormaPago(FormaPago formaPago) { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null;//from w w w.j a va2 s . c om String sql = "insert into forma_pago (descripcion) values (?)"; try { connection = dataSource.getConnection(); connection.setAutoCommit(false); preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); preparedStatement.setString(1, formaPago.getDescripcion()); preparedStatement.execute(); connection.commit(); resultSet = preparedStatement.getGeneratedKeys(); resultSet.next(); formaPago.setId(resultSet.getInt(1)); return formaPago; } catch (Exception e) { } finally { if (preparedStatement != null) { try { preparedStatement.close(); } catch (Exception e) { } } if (connection != null) { try { connection.close(); } catch (Exception e) { } } } return null; }
From source file:eu.ibacz.swsc.spring.di.testdependencyinjection.dao.impl.JdbcTemplateCustomerDaoImpl.java
public void save(final Customer customer) { KeyHolder keyHolder = new GeneratedKeyHolder(); jdbcTemplate.update(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement stmt = connection.prepareStatement( "insert into customer (firstname, lastname) values (?,?)", Statement.RETURN_GENERATED_KEYS); stmt.setString(1, customer.getFirstname()); stmt.setString(2, customer.getLastname()); return stmt; }//ww w . jav a 2s . c o m }, keyHolder); customer.setId(keyHolder.getKey().longValue()); }
From source file:zerogame.info.javapay.dao.PayOrderDao.java
@Override public PayOrder add(final PayOrder payorder) { try {/*from w ww . jav a 2 s . c o m*/ KeyHolder keyHolder = new GeneratedKeyHolder(); getTemplate().update(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection con) throws SQLException { PreparedStatement ps = con.prepareStatement("insert into pay_order" + "(uin,account_id,order_id,product_id,product_name,product_desc,money,channel,serverId,status,order_type,create_time,user_level,vip_level) " + "values(?,?,?,?,?,?,?,?,?,?,?,now(),?,?)", Statement.RETURN_GENERATED_KEYS); ps.setLong(1, payorder.getUin()); ps.setString(2, payorder.getAccountId()); ps.setString(3, payorder.getOrderId()); ps.setString(4, payorder.getProductId()); ps.setString(5, payorder.getProductName()); ps.setString(6, payorder.getProductDesc()); ps.setInt(7, payorder.getMoney()); ps.setInt(8, payorder.getChannel()); ps.setInt(9, payorder.getServerId()); ps.setInt(10, payorder.getStatus()); ps.setInt(11, payorder.getOrderType()); ps.setInt(12, payorder.getUserLevel()); ps.setInt(13, payorder.getUserVipLevel()); return ps; } }, keyHolder); return payorder; } catch (Exception e) { logger.warn("add pay order failed", e); return null; } }
From source file:org.biblionum.ouvrage.modele.OuvrageTypeModele.java
/** * Java method that inserts a row in the generated sql table and returns the * new generated id/*from w w w . j a v a2 s . co m*/ * * @param con (open java.sql.Connection) * @param designation_typeou * @return id (database row id [id]) * @throws SQLException */ public int insertIntoOuvragetype(DataSource ds, String designation_typeou) throws SQLException { con = ds.getConnection(); int generatedId = -1; String sql = "INSERT INTO ouvragetype (designation_typeou)" + "VALUES (?)"; PreparedStatement statement = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); statement.setString(1, designation_typeou); statement.execute(); ResultSet auto = statement.getGeneratedKeys(); if (auto.next()) { generatedId = auto.getInt(1); } else { generatedId = -1; } statement.close(); con.close(); return generatedId; }