Package org.springframework.jdbc.support

Examples of org.springframework.jdbc.support.GeneratedKeyHolder


            sql.append(")");
        }
        logger.debug("SQL for Save: " + sql);
        int updateCount = 0;
        if (isNewRow && persistentObject.isUsingGeneratedKeysStrategy()) {
            KeyHolder keyHolder = new GeneratedKeyHolder();
            final String prepSql = sql.toString();
            updateCount = getJdbcTemplate().update(new PreparedStatementCreator() {
                public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                    PreparedStatement ps = con.prepareStatement(prepSql, Statement.RETURN_GENERATED_KEYS);
                    int cnt = 0;
View Full Code Here


public class UserDaoImpl extends JdbcDaoSupport implements UserDao {

    public User createUser(final User user) {
        final String sql = "insert into sys_users(username, password, salt, locked) values(?,?,?, ?)";

        GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
        getJdbcTemplate().update(new PreparedStatementCreator() {
            @Override
            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;
    }
View Full Code Here

   *         getKey()一个数字主键<br>
   *         getKeys()复合主键Map结构<br>
   *         getKeyList()多个主键由多个Map组成的List
   */
  public KeyHolder updateNamedParamer(String hql, SqlParameterSource sps) {
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.getSimpleJdbcTemplate().getNamedParameterJdbcOperations().update(
        hql, sps, keyHolder);
    return keyHolder;
  }
View Full Code Here

   */
  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()) {
      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 specificed. " +
            "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 retreiving 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.  Has to be done with the same
      // connection.
      jdbcTemplate.execute(new ConnectionCallback() {
        public Object doInConnection(Connection con) throws SQLException, DataAccessException {
          // Do the insert
          PreparedStatement ps = null;
          try {
            ps = con.prepareStatement(getInsertString());
            setParameterValues(ps, values, null);
            ps.executeUpdate();
          } finally {
            JdbcUtils.closeStatement(ps);
          }
          //Get the key
          String keyQuery = tableMetaDataContext.getSimulationQueryForGetGeneratedKey(
              tableMetaDataContext.getTableName(),
              getGeneratedKeyNames()[0]);
          Statement keyStmt = null;
          ResultSet rs = null;
          HashMap keys = new HashMap(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);
          }
View Full Code Here

   */
  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()) {
      jdbcTemplate.update(
          new PreparedStatementCreator() {
            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 specificed. " +
            "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 retreiving 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 = tableMetaDataContext.getSimulationQueryForGetGeneratedKey(
          tableMetaDataContext.getTableName(),
          getGeneratedKeyNames()[0]);
      Assert.notNull(keyQuery, "Query for simulating get generated keys can't be null");
      if (keyQuery.toUpperCase().startsWith("RETURNING")) {
        Long key = jdbcTemplate.queryForLong(
            getInsertString() + " " + keyQuery,
            values.toArray(new Object[values.size()]));
        HashMap keys = new HashMap(1);
        keys.put(getGeneratedKeyNames()[0], key);
        keyHolder.getKeyList().add(keys);
      }
      else {
        jdbcTemplate.execute(new ConnectionCallback() {
          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;
            HashMap keys = new HashMap(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);
            }
View Full Code Here

         }
     return resultSet.size();
   }

   public int executeInsert(IMockController controller, IQuery query) {
      KeyHolder holder = new GeneratedKeyHolder();
      int types[] = new int[query.getParametersLength()];
      int i = 0;
      for ( IQueryParameter p : query ){
         types[i++] = StatementCreatorUtils.javaTypeToSqlParameterType(p.getColumnMetadata().getType());
      }
      int res = getWriteJdbcTemplate().update(
               new PreparedStatementCreatorFactory(query.getSql(),types)
               .newPreparedStatementCreator(query.getParameterValues()), holder);
      if ( holder != null && holder.getKeyList().size() == 1 ){
         for ( ColumnMetadata col : controller.getColumns().values() ){
            if ( col.isIdentity() == Boolean.TRUE ){
               Number number = holder.getKey();
               if ( Long.class.isAssignableFrom(col.getType()) ){
                  controller.setValue(col.getSetterMethod(), (Long)number);
               }
               //TODO handle other types
               break;
View Full Code Here

   */
  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()) {
      jdbcTemplate.update(
          new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
              PreparedStatement ps = prepareStatementForGeneratedKeys(con);
              setParameterValues(ps, values, null);
              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 specificed. " +
            "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 retreiving 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 = tableMetaDataContext.getSimulationQueryForGetGeneratedKey(
          tableMetaDataContext.getTableName(),
          getGeneratedKeyNames()[0]);
      Assert.notNull(keyQuery, "Query for simulating get generated keys can't be null");
      if (keyQuery.toUpperCase().startsWith("RETURNING")) {
        Long key = jdbcTemplate.queryForLong(
            getInsertString() + " " + keyQuery,
            values.toArray(new Object[values.size()]));
        HashMap keys = new HashMap(1);
        keys.put(getGeneratedKeyNames()[0], key);
        keyHolder.getKeyList().add(keys);
      }
      else {
        jdbcTemplate.execute(new ConnectionCallback() {
          public Object doInConnection(Connection con) throws SQLException, DataAccessException {
            // Do the insert
            PreparedStatement ps = null;
            try {
              ps = con.prepareStatement(getInsertString());
              setParameterValues(ps, values, null);
              ps.executeUpdate();
            } finally {
              JdbcUtils.closeStatement(ps);
            }
            //Get the key
            Statement keyStmt = null;
            ResultSet rs = null;
            HashMap keys = new HashMap(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);
            }
View Full Code Here

    replay();
    ctrlResultSet.replay();
    ctrlResultSetMetaData.replay();

    GeneratedKeysUpdater pc = new GeneratedKeysUpdater();
    KeyHolder generatedKeyHolder = new GeneratedKeyHolder();
    int rowsAffected = pc.run("rod", generatedKeyHolder);
    assertEquals(1, rowsAffected);
    assertEquals(1, generatedKeyHolder.getKeyList().size());
    assertEquals(11, generatedKeyHolder.getKey().intValue());
  }
View Full Code Here

          public void doInTransactionWithoutResult(TransactionStatus transactionStatus)
          {
            try
            {
              Date timestamp = new Date();
              KeyHolder keyHolder = new GeneratedKeyHolder();
              jdbcTemplate.update(
                  getEbMSMessagePreparedStatement(
                      timestamp,
                      message.getMessageHeader().getCPAId(),
                      message.getMessageHeader().getConversationId(),
                      message.getMessageOrder() == null ? null : message.getMessageOrder().getSequenceNumber().getValue().longValue(),
                      message.getMessageHeader().getMessageData().getMessageId(),
                      message.getMessageHeader().getMessageData().getRefToMessageId(),
                      message.getMessageHeader().getFrom().getRole(),
                      message.getMessageHeader().getTo().getRole(),
                      message.getMessageHeader().getService().getType(),
                      message.getMessageHeader().getService().getValue(),
                      message.getMessageHeader().getAction(),
                      XMLMessageBuilder.getInstance(MessageHeader.class).handle(message.getMessageHeader()),
                      XMLMessageBuilder.getInstance(SyncReply.class).handle(message.getSyncReply()),
                      XMLMessageBuilder.getInstance(MessageOrder.class).handle(message.getMessageOrder()),
                      XMLMessageBuilder.getInstance(AckRequested.class).handle(message.getAckRequested()),
                      XMLMessageBuilder.getInstance(Manifest.class).handle(message.getManifest())
                  ),
                  keyHolder
              );
         
              for (DataSource attachment : message.getAttachments())
              {
                simpleJdbcTemplate.update
                (
                  "insert into ebms_attachment (" +
                    "ebms_message_id," +
                    "name," +
                    "content_type," +
                    "content" +
                  ") values (?,?,?,?)",
                  keyHolder.getKey().longValue(),
                  attachment.getName() == null ? Constants.DEFAULT_FILENAME : attachment.getName(),
                  attachment.getContentType().split(";")[0].trim(),
                  IOUtils.toByteArray(attachment.getInputStream())
                );
              }

              List<Object[]> events = new ArrayList<Object[]>();
              for (EbMSSendEvent sendEvent : sendEvents)
              {
                //events.add(new Object[]{keyHolder.getKey().longValue(),String.format(getDateFormat(),sendEvent.getTime())});
                events.add(new Object[]{keyHolder.getKey().longValue(),sendEvent.getTime()});
              }
              simpleJdbcTemplate.batchUpdate
              (
                "insert into ebms_send_event (" +
                  "ebms_message_id," +
View Full Code Here

          public void doInTransactionWithoutResult(TransactionStatus transactionStatus)
          {
            try
            {
              Date timestamp = new Date();
              KeyHolder keyHolder = new GeneratedKeyHolder();
              jdbcTemplate.update(
                  getEbMSMessagePreparedStatement(
                      timestamp,
                      message.getMessageHeader().getCPAId(),
                      message.getMessageHeader().getConversationId(),
                      message.getMessageOrder() == null ? null : message.getMessageOrder().getSequenceNumber().getValue().longValue(),
                      message.getMessageHeader().getMessageData().getMessageId(),
                      message.getMessageHeader().getMessageData().getRefToMessageId(),
                      message.getMessageHeader().getFrom().getRole(),
                      message.getMessageHeader().getTo().getRole(),
                      message.getMessageHeader().getService().getType(),
                      message.getMessageHeader().getService().getValue(),
                      message.getMessageHeader().getAction(),
                      message.getOriginal(),
                      XMLMessageBuilder.getInstance(SignatureType.class).handle(new ObjectFactory().createSignature(message.getSignature())),
                      XMLMessageBuilder.getInstance(MessageHeader.class).handle(message.getMessageHeader()),
                      XMLMessageBuilder.getInstance(SyncReply.class).handle(message.getSyncReply()),
                      XMLMessageBuilder.getInstance(MessageOrder.class).handle(message.getMessageOrder()),
                      XMLMessageBuilder.getInstance(AckRequested.class).handle(message.getAckRequested()),
                      XMLMessageBuilder.getInstance(Manifest.class).handle(message.getManifest()),
                      status
                  ),
                  keyHolder
              );
         
              for (DataSource attachment : message.getAttachments())
              {
                simpleJdbcTemplate.update
                (
                  "insert into ebms_attachment (" +
                    "ebms_message_id," +
                    "name," +
                    "content_type," +
                    "content" +
                  ") values (?,?,?,?)",
                  keyHolder.getKey().longValue(),
                  attachment.getName() == null ? Constants.DEFAULT_FILENAME : attachment.getName(),
                  attachment.getContentType().split(";")[0].trim(),
                  IOUtils.toByteArray(attachment.getInputStream())
                );
              }
View Full Code Here

TOP

Related Classes of org.springframework.jdbc.support.GeneratedKeyHolder

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.