List of usage examples for java.sql PreparedStatement getGeneratedKeys
ResultSet getGeneratedKeys() throws SQLException;
Statement
object. From source file:com.adanac.module.blog.dao.AnswerDao.java
public Integer save(final Integer questionId, final String visitorIp, final Date answerDate, final String answer, final String username, final Integer referenceAnswerId) { return execute(new TransactionalOperation<Integer>() { @Override//www .jav a 2 s . c o m public Integer doInConnection(Connection connection) { try { PreparedStatement statement = null; if (referenceAnswerId == null) { statement = connection.prepareStatement( "insert into answers (visitor_ip,city,answer,question_id," + "answer_date,username) values (?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS); } else { statement = connection.prepareStatement( "insert into answers (visitor_ip,city,answer,question_id," + "answer_date,username,reference_answer_id) values (?,?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS); } statement.setString(1, visitorIp); statement.setString(2, Configuration.isProductEnv() ? HttpApiHelper.getCity(visitorIp) : "?"); statement.setString(3, answer); statement.setInt(4, questionId); Date finalCommentDate = answerDate; if (answerDate == null) { finalCommentDate = new Date(); } statement.setTimestamp(5, new Timestamp(finalCommentDate.getTime())); statement.setString(6, username); if (referenceAnswerId != null) { statement.setInt(7, referenceAnswerId); } int result = statement.executeUpdate(); if (result > 0) { ResultSet resultSet = statement.getGeneratedKeys(); if (resultSet.next()) { return resultSet.getInt(1); } } } catch (SQLException e) { error("save answers failed ...", e); } return null; } }); }
From source file:com.skilrock.lms.coreEngine.scratchService.orderMgmt.common.AgentOrderProcessHelper.java
/** * This method is used for generating order for a retailer. Returns true if * the order is successfully generated//from w ww.ja v a2 s . c o m * * @param userId * @param cartList * @param retOrgList * @param retOrgName * @return boolean * @throws LMSException */ public int generateOrder(int userId, List<GameBean> cartList, List<OrgBean> retOrgList, String retOrgName, int userOrgId) throws LMSException { int retOrgId = -1; int retailerId = -1; if (retOrgList != null) { OrgBean bean = null; for (int i = 0; i < retOrgList.size(); i++) { bean = retOrgList.get(i); logger.debug("---OrG Name::" + bean.getOrgName()); if (retOrgName.equals(bean.getOrgName())) { retOrgId = bean.getOrgId(); retailerId = bean.getUserId(); logger.debug("RetOrgId::" + retOrgId); logger.debug("retailerId::" + retailerId); break; } } } logger.debug("RetOrgId::" + retOrgId); logger.debug("retailerId::" + retailerId); Connection connection = null; PreparedStatement orderPstmt = null; PreparedStatement gamePstmt = null; ResultSet resultSet = null; int orderId = -1; if (cartList != null) { int size = cartList.size(); // QueryManager queryManager = null; GameBean gameBean = null; String orderQuery = null; String gameQuery = null; if (size > 0) { try { // create database connection connection = DBConnect.getConnection(); connection.setAutoCommit(false); // get order query orderQuery = QueryManager.getST1InsertAgtOrderQuery(); orderPstmt = connection.prepareStatement(orderQuery); // get ordered game query gameQuery = QueryManager.getST1InsertAgtOrderedGamesQuery(); gamePstmt = connection.prepareStatement(gameQuery); // set parameters for insert into order table orderPstmt.setInt(1, userId); orderPstmt.setInt(2, retailerId); orderPstmt.setInt(3, retOrgId); orderPstmt.setDate(4, new java.sql.Date(new Date().getTime())); orderPstmt.setString(5, "APPROVED"); orderPstmt.setString(6, "Y"); orderPstmt.setInt(7, userOrgId); orderPstmt.execute(); resultSet = orderPstmt.getGeneratedKeys(); while (resultSet.next()) { orderId = resultSet.getInt(1); } logger.debug("OrderId::" + orderId); // set parameters for insert into ordered games table for (int i = 0; i < size; i++) { gameBean = cartList.get(i); logger.debug("1:" + gameBean.getGameId()); logger.debug("2:" + gameBean.getOrderedQty()); gamePstmt.setInt(1, orderId); gamePstmt.setInt(2, gameBean.getGameId()); gamePstmt.setInt(3, gameBean.getOrderedQty()); gamePstmt.setInt(4, gameBean.getOrderedQty()); gamePstmt.execute(); } // commit the connection connection.commit(); return orderId; } catch (SQLException e) { try { connection.rollback(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } e.printStackTrace(); throw new LMSException(e); } finally { try { if (orderPstmt != null) { orderPstmt.close(); } if (gamePstmt != null) { gamePstmt.close(); } if (connection != null) { connection.close(); } } catch (SQLException se) { se.printStackTrace(); } } } } return orderId; }
From source file:com.flexoodb.engines.FlexJAXBMappedDBDataEngine.java
private Object persist(Object obj, Connection conn, String targettable) throws Exception { // check if the object has a table String tablename = (targettable == null ? ((FlexContainer) obj).getObject().getClass().getSimpleName() : targettable).toLowerCase(); tablename = tablename.endsWith("type") ? tablename.substring(0, tablename.lastIndexOf("type")) : tablename; String id = ((FlexContainer) obj).getId(); String parentid = ((FlexContainer) obj).getParentId(); Object obj2 = ((FlexContainer) obj).getObject(); // retrieve the methods of the object and use as param. FlexElement element = null;//from ww w .j av a 2s . co m if (tablename.indexOf("_") > -1) { element = _elements.get(tablename.substring(tablename.indexOf("_") + 1)); } else { element = _elements.get(tablename); } String idcolumn = element.getAttribute("idcolumn").getValue(); String realtablename = element.getAttribute("realtablename").getValue(); String parentidcolumn = element.getAttribute("parentidcolumn").getValue(); String autoincrement = element.getAttribute("autoincrement").getValue(); boolean includeidcolumns = element.getAttribute("includeidcolumns").getValue() == null ? false : (element.getAttribute("includeidcolumns").getValue().equalsIgnoreCase("true")); if (!autoincrement.equalsIgnoreCase("true")) { if (id == null || id.isEmpty()) { id = getNewId(); FlexUtils.setId(id, (FlexContainer) obj); } if (parentid == null || parentid.isEmpty()) { ((FlexContainer) obj).setParentId(id); } } StringBuffer fields = new StringBuffer(); StringBuffer entries = new StringBuffer(); Hashtable<String, Object[]> fieldswithcontent = getNonNullObjectFields(tablename, idcolumn, parentidcolumn, id, parentid, obj2, element); Enumeration en = fieldswithcontent.keys(); while (en.hasMoreElements()) { String field = (String) en.nextElement(); //boolean ok = true; fields.append(",`" + field + "`"); entries.append(",?"); } //System.out.println(">>>insert into "+tablename.toLowerCase()+" ("+fields.substring(1)+") values ("+entries.substring(1)+")"); PreparedStatement ps = null; if (autoincrement.equalsIgnoreCase("true")) { ps = (PreparedStatement) conn.prepareStatement( "insert into " + ((realtablename != null && !_shared) ? realtablename : tablename.toLowerCase()) + " (" + fields.substring(1) + ") values (" + entries.substring(1) + ")", Statement.RETURN_GENERATED_KEYS); // then we get the preparedstatement updatePreparedStatement(tablename, fieldswithcontent, ps); ps.executeUpdate(); ResultSet keys = ps.getGeneratedKeys(); keys.next(); int newkey = keys.getInt(1); keys.close(); FlexUtils.setId(newkey + "", (FlexContainer) obj); if (parentid == null || parentid.isEmpty()) { ((FlexContainer) obj).setParentId(newkey + ""); } FlexUtils.setObjectMethod(((FlexContainer) obj).getObject(), idcolumn, new BigInteger(newkey + "")); } else { ps = (PreparedStatement) conn.prepareStatement( "insert into " + ((realtablename != null && !_shared) ? realtablename : tablename.toLowerCase()) + " (" + fields.substring(1) + ") values (" + entries.substring(1) + ")"); // then we get the preparedstatement updatePreparedStatement(tablename, fieldswithcontent, ps); ps.executeUpdate(); } ps.close(); return obj; }
From source file:org.wso2.intcloud.core.dao.ApplicationDAO.java
/** * Method for adding version details to database. * * @param dbConnection database connection * @param version version object//ww w .j a v a 2 s. c o m * @param applicationId application id * @param tenantId tenant id * @return * @throws IntCloudException */ public void addVersion(Connection dbConnection, Version version, int applicationId, int tenantId) throws IntCloudException { PreparedStatement preparedStatement = null; int versionId = 0; ResultSet resultSet = null; try { preparedStatement = dbConnection.prepareStatement(SQLQueryConstants.ADD_VERSION, Statement.RETURN_GENERATED_KEYS); preparedStatement.setString(1, version.getVersionName()); preparedStatement.setString(2, version.getHashId()); preparedStatement.setInt(3, applicationId); preparedStatement.setInt(4, version.getRuntimeId()); preparedStatement.setInt(5, tenantId); preparedStatement.execute(); resultSet = preparedStatement.getGeneratedKeys(); while (resultSet.next()) { versionId = resultSet.getInt(1); } // List<Tag> tags = version.getTags(); // if (tags != null) { // addTags(dbConnection, tags, version.getHashId(), tenantId); // } // // List<RuntimeProperty> runtimeProperties = version.getRuntimeProperties(); // if (runtimeProperties != null) { // addRunTimeProperties(dbConnection, runtimeProperties, version.getHashId(), tenantId); // } } catch (SQLException e) { String msg = "Error occurred while adding application version to database for application id : " + applicationId + " version : " + version.getVersionName() + " in tenant : " + tenantId; log.error(msg, e); throw new IntCloudException(msg, e); } finally { DBUtil.closeResultSet(resultSet); DBUtil.closePreparedStatement(preparedStatement); } }
From source file:org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.GenericOperationDAOImpl.java
public int addOperation(Operation operation) throws OperationManagementDAOException { PreparedStatement stmt = null; ResultSet rs = null;//w w w . j a v a2 s . co m try { Connection connection = OperationManagementDAOFactory.getConnection(); String sql = "INSERT INTO DM_OPERATION(TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE) " + "VALUES (?, ?, ?, ?)"; stmt = connection.prepareStatement(sql, new String[] { "id" }); stmt.setString(1, operation.getType().toString()); stmt.setTimestamp(2, new Timestamp(new Date().getTime())); stmt.setTimestamp(3, null); stmt.setString(4, operation.getCode()); stmt.executeUpdate(); rs = stmt.getGeneratedKeys(); int id = -1; if (rs.next()) { id = rs.getInt(1); } return id; } catch (SQLException e) { throw new OperationManagementDAOException("Error occurred while adding operation metadata", e); } finally { OperationManagementDAOUtil.cleanupResources(stmt, rs); } }
From source file:org.wso2.carbon.device.mgt.core.dao.impl.ApplicationDAOImpl.java
@Override public List<Integer> addApplications(List<Application> applications, int tenantId) throws DeviceManagementDAOException { Connection conn;//w ww . j av a 2s .com PreparedStatement stmt = null; ResultSet rs; ByteArrayOutputStream bao = null; ObjectOutputStream oos = null; List<Integer> applicationIds = new ArrayList<>(); try { conn = this.getConnection(); stmt = conn.prepareStatement("INSERT INTO DM_APPLICATION (NAME, PLATFORM, CATEGORY, " + "VERSION, TYPE, LOCATION_URL, IMAGE_URL, TENANT_ID,APP_PROPERTIES, APP_IDENTIFIER, MEMORY_USAGE, IS_ACTIVE) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", new String[] { "id" }); for (Application application : applications) { stmt.setString(1, application.getName()); stmt.setString(2, application.getPlatform()); stmt.setString(3, application.getCategory()); stmt.setString(4, application.getVersion()); stmt.setString(5, application.getType()); stmt.setString(6, application.getLocationUrl()); stmt.setString(7, application.getImageUrl()); stmt.setInt(8, tenantId); bao = new ByteArrayOutputStream(); oos = new ObjectOutputStream(bao); oos.writeObject(application.getAppProperties()); stmt.setBytes(9, bao.toByteArray()); stmt.setString(10, application.getApplicationIdentifier()); stmt.setInt(11, application.getMemoryUsage()); stmt.setBoolean(12, application.isActive()); stmt.executeUpdate(); rs = stmt.getGeneratedKeys(); if (rs.next()) { applicationIds.add(rs.getInt(1)); } } return applicationIds; } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while adding bulk application list", e); } catch (IOException e) { throw new DeviceManagementDAOException("Error occurred while serializing application properties object", e); } finally { if (bao != null) { try { bao.close(); } catch (IOException e) { log.warn("Error occurred while closing ByteArrayOutputStream", e); } } if (oos != null) { try { oos.close(); } catch (IOException e) { log.warn("Error occurred while closing ObjectOutputStream", e); } } DeviceManagementDAOUtil.cleanupResources(stmt, null); } }
From source file:org.forgerock.openidm.repo.jdbc.impl.GenericTableHandler.java
@Override public void create(String fullId, String type, String localId, Map<String, Object> obj, Connection connection) throws SQLException, IOException, InternalServerErrorException { long typeId = getTypeId(type, connection); // Note this call can commit and start a new transaction in some cases PreparedStatement createStatement = null; try {//from www. j a va 2 s. c om createStatement = queries.getPreparedStatement(connection, queryMap.get(QueryDefinition.CREATEQUERYSTR), true); logger.debug("Create with fullid {}", fullId); String rev = "0"; obj.put("_id", localId); // Save the id in the object obj.put("_rev", rev); // Save the rev in the object, and return the changed rev from the create. String objString = mapper.writeValueAsString(obj); logger.trace("Populating statement {} with params {}, {}, {}, {}", queryMap.get(QueryDefinition.CREATEQUERYSTR), typeId, localId, rev, objString); createStatement.setLong(1, typeId); createStatement.setString(2, localId); createStatement.setString(3, rev); createStatement.setString(4, objString); logger.debug("Executing: {}", createStatement); int val = createStatement.executeUpdate(); ResultSet keys = createStatement.getGeneratedKeys(); boolean validKeyEntry = keys.next(); if (!validKeyEntry) { throw new InternalServerErrorException( "Object creation for " + fullId + " failed to retrieve an assigned ID from the DB."); } long dbId = keys.getLong(1); logger.debug("Created object for id {} with rev {}", fullId, rev); JsonValue jv = new JsonValue(obj); writeValueProperties(fullId, dbId, localId, jv, connection); } finally { CleanupHelper.loggedClose(createStatement); } }
From source file:com.mmnaseri.dragonfly.data.impl.DefaultDataAccess.java
@Override public <E> E insert(E entity) { final Map<Object, Object> saveQueue = this.saveQueue.get(); if (saveQueue.containsKey(entity)) { //noinspection unchecked return (E) saveQueue.get(entity); }//ww w.java2 s .co m saveQueueLock.set(saveQueueLock.get() + 1); final EntityHandler<E> entityHandler = entityHandlerContext.getHandler(entity); final E enhancedEntity = getEnhancedEntity(entity); saveQueue.put(entity, enhancedEntity); final InitializedEntity<E> initializedEntity = getInitializedEntity(enhancedEntity); initializedEntity.freeze(); entityHandler.initializeVersion(enhancedEntity); final Map<String, Object> sequenceValues = new HashMap<String, Object>(); sequenceValues.putAll(session.getDatabaseDialect().loadTableValues( session.getTableMetadataRegistry().getTableMetadata(TableKeyGeneratorEntity.class), session.getTableMetadataRegistry().getTableMetadata(entityHandler.getEntityType()), session)); sequenceValues.putAll(session.getDatabaseDialect().loadSequenceValues( session.getTableMetadataRegistry().getTableMetadata(entityHandler.getEntityType()))); entityHandler.fromMap(enhancedEntity, sequenceValues); entityHandler.saveDependencyRelations(enhancedEntity, this); eventHandler.beforeInsert(enhancedEntity); final PreparedStatement preparedStatement = internalExecuteUpdate(entityHandler.getEntityType(), Statements.Manipulation.INSERT, MapTools.prefixKeys(entityHandler.toMap(enhancedEntity), "value.")); if (entityHandler.hasKey() && entityHandler.isKeyAutoGenerated()) { if (isInBatchMode()) { deferredKeys.get().add(enhancedEntity); } else { try { final ResultSet generatedKeys = preparedStatement.getGeneratedKeys(); if (generatedKeys.next()) { entityHandler.setKey(enhancedEntity, session.getDatabaseDialect().retrieveKey(generatedKeys)); } if (initializedEntity.getInitializationContext() == null) { final DefaultEntityInitializationContext entityInitializationContext = new DefaultEntityInitializationContext( this, initializationContext); entityInitializationContext.register(entityHandler.getEntityType(), entityHandler.getKey(enhancedEntity), enhancedEntity); initializedEntity.setInitializationContext(entityInitializationContext); } } catch (SQLException e) { throw new UnsupportedOperationException("Failed to retrieve auto-generated keys", e); } } } entityHandler.incrementVersion(enhancedEntity); if (!isInBatchMode()) { cleanUpStatement(preparedStatement); } initializedEntity.setOriginalCopy(enhancedEntity); eventHandler.afterInsert(enhancedEntity); saveDependents(entityHandler, enhancedEntity); saveQueueLock.set(saveQueueLock.get() - 1); if (saveQueueLock.get() == 0) { saveQueue.remove(entity); for (Object object : deferredSaveQueue.get()) { saveQueue.remove(object); } deferredSaveQueue.get().clear(); } else { deferredSaveQueue.get().add(entity); } entityHandler.copy(enhancedEntity, entity); initializedEntity.unfreeze(); return enhancedEntity; }
From source file:org.wso2.carbon.registry.core.jdbc.dao.JDBCCommentsVersionDAO.java
/** * Method to persist a comment.// www.j a va2 s.c om * * @param resource the resource * @param userID the id of the user who added the comment. * @param comment the comment to be persisted. * * @return the comment id of the newly added comment. * @throws RegistryException if some error occurs while adding a comment */ public int addComment(ResourceImpl resource, String userID, Comment comment) throws RegistryException { JDBCDatabaseTransaction.ManagedRegistryConnection conn = JDBCDatabaseTransaction.getConnection(); PreparedStatement ps1 = null, ps2 = null, ps3 = null; int commentId = -1; try { String sql1 = "INSERT INTO REG_COMMENT (REG_COMMENT_TEXT," + "REG_USER_ID, REG_COMMENTED_TIME, REG_TENANT_ID) VALUES (?, ?, ?, ?)"; String sql2 = "SELECT MAX(REG_ID) FROM REG_COMMENT"; String sql3 = "INSERT INTO REG_RESOURCE_COMMENT (REG_COMMENT_ID, " + "REG_VERSION, REG_TENANT_ID) VALUES (?, ?, ?)"; String dbProductName = conn.getMetaData().getDatabaseProductName(); boolean returnsGeneratedKeys = DBUtils.canReturnGeneratedKeys(dbProductName); if (returnsGeneratedKeys) { ps1 = conn.prepareStatement(sql1, new String[] { DBUtils.getConvertedAutoGeneratedColumnName(dbProductName, DatabaseConstants.ID_FIELD) }); } else { ps1 = conn.prepareStatement(sql1); } ps3 = conn.prepareStatement(sql3); // prepare to execute query2 for the comments ps1.setString(1, comment.getText()); ps1.setString(2, userID); long now = System.currentTimeMillis(); ps1.setTimestamp(3, new Timestamp(now)); ps1.setInt(4, CurrentSession.getTenantId()); ResultSet resultSet1; if (returnsGeneratedKeys) { ps1.executeUpdate(); resultSet1 = ps1.getGeneratedKeys(); } else { synchronized (ADD_COMMENT_LOCK) { ps1.executeUpdate(); ps2 = conn.prepareStatement(sql2); resultSet1 = ps2.executeQuery(); } } try { if (resultSet1.next()) { // setting the RES_COMMENTS_ID commentId = resultSet1.getInt(1); ps3.setInt(1, commentId); ps3.setLong(2, resource.getVersionNumber()); ps3.setInt(3, CurrentSession.getTenantId()); ps3.executeUpdate(); } } finally { if (resultSet1 != null) { resultSet1.close(); } } } catch (SQLException e) { String msg = "Failed to add comments to the resource " + resource.getPath() + ". " + e.getMessage(); log.error(msg, e); throw new RegistryException(msg, e); } finally { try { try { if (ps1 != null) { ps1.close(); } } finally { try { if (ps2 != null) { ps2.close(); } } finally { if (ps3 != null) { ps3.close(); } } } } catch (SQLException ex) { String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR; log.error(msg, ex); } } return commentId; }
From source file:org.wso2.carbon.user.core.tenant.JDBCTenantManager.java
public int addTenant(org.wso2.carbon.user.api.Tenant tenant) throws UserStoreException { // if tenant id present in tenant bean, we create the tenant with that tenant id. if (tenant.getId() > 0) { return addTenantWithGivenId(tenant); }//from w w w.j av a 2 s . c o m Connection dbConnection = null; PreparedStatement prepStmt = null; ResultSet result = null; int id = 0; try { dbConnection = getDBConnection(); String sqlStmt = TenantConstants.ADD_TENANT_SQL; String dbProductName = dbConnection.getMetaData().getDatabaseProductName(); prepStmt = dbConnection.prepareStatement(sqlStmt, new String[] { DBUtils.getConvertedAutoGeneratedColumnName(dbProductName, "UM_ID") }); prepStmt.setString(1, tenant.getDomain().toLowerCase()); prepStmt.setString(2, tenant.getEmail()); Date createdTime = tenant.getCreatedDate(); long createdTimeMs; if (createdTime == null) { createdTimeMs = System.currentTimeMillis(); } else { createdTimeMs = createdTime.getTime(); } prepStmt.setTimestamp(3, new Timestamp(createdTimeMs)); String realmConfigString = RealmConfigXMLProcessor .serialize((RealmConfiguration) tenant.getRealmConfig()).toString(); InputStream is = new ByteArrayInputStream(realmConfigString.getBytes()); prepStmt.setBinaryStream(4, is, is.available()); prepStmt.executeUpdate(); result = prepStmt.getGeneratedKeys(); if (result.next()) { id = result.getInt(1); } dbConnection.commit(); } catch (Exception e) { DatabaseUtil.rollBack(dbConnection); String msg = "Error in adding tenant with " + "tenant domain: " + tenant.getDomain().toLowerCase() + "."; if (log.isDebugEnabled()) { log.debug(msg, e); } throw new UserStoreException(msg, e); } finally { DatabaseUtil.closeAllConnections(dbConnection, result, prepStmt); } return id; }