List of usage examples for org.springframework.jdbc.core PreparedStatementCreator PreparedStatementCreator
PreparedStatementCreator
From source file:com.onclave.testbench.jdbcTemplate.DAOSupport.StudentDAOImplementation.java
@Override public boolean deleteStudent(final long idStudent) { final int result = jdbcTemplate.update(new PreparedStatementCreator() { @Override/*from w ww. j a va2 s . c om*/ public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement preparedStatement = connection .prepareStatement(QueryStatements.DELETE_STUDENT_BY_ID_SQL); preparedStatement.setLong(1, idStudent); return preparedStatement; } }); if (result > 0) { return true; } return false; }
From source file:org.pegadi.server.score.ScoreServerImpl.java
/** * Starts score recording for a new game. The <code>Score</code> object that is * returned <i>must</i> be used when calling {@link #updateScore } and * {@link #endGame }, as each score has an unique ID. * * @param domain The domain for the game. * @return A new Score object, with the score set to 0. If the domain is not known, * this method will return <code>null</code>. *///from www . j av a 2 s . c om public Score startGame(final Person person, String domain) { if (domain.equals("tetris")) { final String insertSql = "insert into score_tetris (userID, score, level, linecount, starttime, active) values (?, ?, ?, ?, ?, true)"; KeyHolder keyHolder = new GeneratedKeyHolder(); // The key/id of the new score is needed template.update(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection con) throws SQLException { PreparedStatement statement = con.prepareStatement(insertSql, new String[] { "ID" }); statement.setString(1, person.getUsername()); statement.setLong(2, 0); // score statement.setInt(3, 1); // level statement.setInt(4, 0); // lines statement.setTimestamp(5, new Timestamp((new GregorianCalendar()).getTimeInMillis())); return statement; } }, keyHolder); int scoreId = keyHolder.getKey().intValue(); return new TetrisScore(scoreId, person.getUsername(), person.getName(), 1); } else { log.error("Domain '{}' not implemented yet!", domain); return null; } }
From source file:com.jagornet.dhcp.db.JdbcIaPrefixDAO.java
public void create(final IaPrefix iaPrefix) { /**// www.j a v a 2 s .com * Note: see https://issues.apache.org/jira/browse/DERBY-3609 * "Formally, Derby does not support getGeneratedKeys since * DatabaseMetaData.supportsGetGeneratedKeys() returns false. * However, Statement.getGeneratedKeys() is partially implemented, * ... since it will only return a meaningful result when an single * row insert is done with INSERT...VALUES" * * Spring has thus provided a workaround as described here: * http://jira.springframework.org/browse/SPR-5306 */ GeneratedKeyHolder newKey = new GeneratedKeyHolder(); getJdbcTemplate().update(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection conn) throws SQLException { PreparedStatement ps = conn.prepareStatement( "insert into iaprefix" + " (prefixaddress, prefixlength, starttime, preferredendtime," + " validendtime, state, identityassoc_id)" + " values (?, ?, ?, ?, ?, ?, ?)", PreparedStatement.RETURN_GENERATED_KEYS); ps.setBytes(1, iaPrefix.getIpAddress().getAddress()); ps.setInt(2, iaPrefix.getPrefixLength()); java.sql.Timestamp sts = new java.sql.Timestamp(iaPrefix.getStartTime().getTime()); ps.setTimestamp(3, sts, Util.GMT_CALENDAR); java.sql.Timestamp pts = new java.sql.Timestamp(iaPrefix.getPreferredEndTime().getTime()); ps.setTimestamp(4, pts, Util.GMT_CALENDAR); java.sql.Timestamp vts = new java.sql.Timestamp(iaPrefix.getValidEndTime().getTime()); ps.setTimestamp(5, vts, Util.GMT_CALENDAR); ps.setByte(6, iaPrefix.getState()); ps.setLong(7, iaPrefix.getIdentityAssocId()); return ps; } }, newKey); Number newId = newKey.getKey(); if (newId != null) { iaPrefix.setId(newId.longValue()); } }
From source file:com.jagornet.dhcp.db.JdbcIaAddressDAO.java
public void create(final IaAddress iaAddr) { /**/*from w w w .java2 s. c o m*/ * Note: see https://issues.apache.org/jira/browse/DERBY-3609 * "Formally, Derby does not support getGeneratedKeys since * DatabaseMetaData.supportsGetGeneratedKeys() returns false. * However, Statement.getGeneratedKeys() is partially implemented, * ... since it will only return a meaningful result when an single * row insert is done with INSERT...VALUES" * * Spring has thus provided a workaround as described here: * http://jira.springframework.org/browse/SPR-5306 */ GeneratedKeyHolder newKey = new GeneratedKeyHolder(); getJdbcTemplate().update(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection conn) throws SQLException { PreparedStatement ps = conn.prepareStatement( "insert into iaaddress" + " (ipaddress, starttime, preferredendtime, validendtime," + " state, identityassoc_id)" + " values (?, ?, ?, ?, ?, ?)", PreparedStatement.RETURN_GENERATED_KEYS); ps.setBytes(1, iaAddr.getIpAddress().getAddress()); java.sql.Timestamp sts = new java.sql.Timestamp(iaAddr.getStartTime().getTime()); ps.setTimestamp(2, sts, Util.GMT_CALENDAR); java.sql.Timestamp pts = new java.sql.Timestamp(iaAddr.getPreferredEndTime().getTime()); ps.setTimestamp(3, pts, Util.GMT_CALENDAR); java.sql.Timestamp vts = new java.sql.Timestamp(iaAddr.getValidEndTime().getTime()); ps.setTimestamp(4, vts, Util.GMT_CALENDAR); ps.setByte(5, iaAddr.getState()); ps.setLong(6, iaAddr.getIdentityAssocId()); return ps; } }, newKey); Number newId = newKey.getKey(); if (newId != null) { iaAddr.setId(newId.longValue()); } }
From source file:net.freechoice.dao.impl.Dao_Transaction.java
@DBSpec(dialect = Dialect.PostgreSQL) @Override// w ww .j a v a 2s . c o m public List<FC_Transaction> getTransactionsOnDate(final Date date) { return getJdbcTemplate().query(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection con) throws SQLException { PreparedStatement ps = con.prepareStatement(SELECT_FROM_FC_TRANSACTION + "where is_valid = true and time_committed::date = ?" + Dao_Transaction.TIME_DESCEND); ps.setDate(1, date); return ps; } }, mapper); }
From source file:com.wwpass.cas.example.JdbcUserServiceDao.java
public void addRole(final int uid, String[] roles) { for (final String role : roles) { getJdbcTemplate().update(new PreparedStatementCreator() { @Override// w w w .j a va 2 s. c om public PreparedStatement createPreparedStatement(Connection con) throws SQLException { PreparedStatement ps = con.prepareStatement(ADD_ROLE); ps.setInt(1, uid); ps.setString(2, role); return ps; } }); } }
From source file:nl.ordina.bag.etl.dao.AbstractBAGMutatiesDAO.java
@Override public long insertMutatiesFile(final java.util.Date dateFrom, final java.util.Date dateTo, final byte[] content) throws DAOException { try {//from w ww .j a va 2 s . c om KeyHolder keyHolder = new GeneratedKeyHolder(); jdbcTemplate.update(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement ps = connection.prepareStatement("insert into bag_mutaties_file (" + " id," + " date_from," + " date_to," + " content" + ") values ((select nvl(max(id),0) + 1 from bag_mutaties_file),trunc(?),trunc(?),?)", new int[] { 1 }); ps.setDate(1, new Date(dateFrom.getTime())); ps.setDate(2, new Date(dateTo.getTime())); ps.setBytes(3, content); return ps; } }, keyHolder); return keyHolder.getKey().longValue(); } catch (DataAccessException e) { throw new DAOException(e); } }
From source file:net.duckling.ddl.service.resource.dao.TagItemDAOImpl.java
@Override public int create(final TagItem tagItem) { GeneratedKeyHolder keyHolder = new GeneratedKeyHolder(); this.getJdbcTemplate().update(new PreparedStatementCreator() { @Override/*from www .j av a 2 s. co m*/ public PreparedStatement createPreparedStatement(Connection conn) throws SQLException { PreparedStatement ps = null; ps = conn.prepareStatement(SQL_CREATE, PreparedStatement.RETURN_GENERATED_KEYS); int i = 0; ps.setInt(++i, tagItem.getTid()); ps.setInt(++i, tagItem.getTgid()); ps.setInt(++i, tagItem.getRid()); ps.setInt(++i, tagItem.getTid()); ps.setInt(++i, tagItem.getTgid()); ps.setInt(++i, tagItem.getRid()); return ps; } }, keyHolder); Number key = keyHolder.getKey(); return (key == null) ? -1 : key.intValue(); }
From source file:ru.org.linux.user.ProfileDao.java
public void writeProfile(@Nonnull final User user, @Nonnull final Profile profile) { String boxlets[] = null;//from ww w. jav a2s.c o m List<String> customBoxlets = profile.getCustomBoxlets(); if (customBoxlets != null) { boxlets = customBoxlets.toArray(new String[customBoxlets.size()]); } final String[] finalBoxlets = boxlets; if (jdbcTemplate.update(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection con) throws SQLException { PreparedStatement st = con .prepareStatement("UPDATE user_settings SET settings=?, main=? WHERE id=?"); st.setObject(1, profile.getSettings()); if (finalBoxlets != null) { st.setArray(2, con.createArrayOf("text", finalBoxlets)); } else { st.setNull(2, Types.ARRAY); } st.setInt(3, user.getId()); return st; } }) == 0) { jdbcTemplate.update(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection con) throws SQLException { PreparedStatement st = con .prepareStatement("INSERT INTO user_settings (id, settings, main) VALUES (?,?,?)"); st.setInt(1, user.getId()); st.setObject(2, profile.getSettings()); if (finalBoxlets != null) { st.setArray(3, con.createArrayOf("text", finalBoxlets)); } else { st.setNull(3, Types.ARRAY); } return st; } }); } }
From source file:com.nortal.petit.orm.statement.InsertStatement.java
@Override public void exec() { prepare();/*w ww .j av a2 s. co m*/ if (!CollectionUtils.isEmpty(getBeans())) { if (getMapping().id() == null) { execBatchUpdate(); } else { final KeyHolder keyHolder = new GeneratedKeyHolder(); final InterceptorCalls interceptorCalls = new InterceptorCalls(); getJdbcTemplate().execute(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection con) throws SQLException { return con.prepareStatement(getSql(), Statement.RETURN_GENERATED_KEYS); } }, new PreparedStatementCallback<Object>() { @Override public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException { MappingParamFunction<B> paramFunction = new MappingParamFunction<B>(getMapping()); for (B bean : getBeans()) { paramFunction.setBean(bean); Object[] params = getParams(paramFunction); Object[] queryParams = params.length == 1 && params[0] instanceof Object[] ? (Object[]) params[0] : params; interceptorCalls.setBeanValues(bean, queryParams); ArgPreparedStatementSetter.setValues(ps, queryParams, 1); ps.executeUpdate(); extractKeys(ps); } return null; } /** * @param ps * @throws SQLException */ private void extractKeys(PreparedStatement ps) throws SQLException { ResultSet keys = ps.getGeneratedKeys(); if (keys != null) { try { RowMapperResultSetExtractor<Map<String, Object>> rse = new RowMapperResultSetExtractor<Map<String, Object>>( new ColumnMapRowMapper(), 1); keyHolder.getKeyList().addAll(rse.extractData(keys)); } finally { JdbcUtils.closeResultSet(keys); } } } }); try { Property<B, Object> idProperty = getMapping().id(); for (int i = 0; i < getBeans().size(); i++) { B bean = getBeans().get(i); Object key = keyHolder.getKeyList().get(i).get(idProperty.column()); idProperty.write(bean, key); interceptorCalls.setBeanId(bean, key); } } catch (Exception e) { throw new PersistenceException("InsertStatement.exec: unable to write bean primary key", e); } interceptorCalls.callInterceptor(); } } else { getJdbcTemplate().update(getSql(), getParams(null)); } }