Example usage for java.sql Statement RETURN_GENERATED_KEYS

List of usage examples for java.sql Statement RETURN_GENERATED_KEYS

Introduction

In this page you can find the example usage for java.sql Statement RETURN_GENERATED_KEYS.

Prototype

int RETURN_GENERATED_KEYS

To view the source code for java.sql Statement RETURN_GENERATED_KEYS.

Click Source Link

Document

The constant indicating that generated keys should be made available for retrieval.

Usage

From source file:net.mindengine.oculus.frontend.service.project.JdbcProjectDAO.java

@Override
public Long createProject(Project project) throws Exception {

    PreparedStatement ps = getConnection().prepareStatement(
            "insert into projects (name, description, path, parent_id, icon, author_id, date) values (?,?,?,?,?,?,?)",
            Statement.RETURN_GENERATED_KEYS);

    ps.setString(1, project.getName());//from w w  w .  j a  v a 2 s. com
    ps.setString(2, project.getDescription());
    ps.setString(3, project.getPath());
    ps.setLong(4, project.getParentId());
    ps.setString(5, project.getIcon());
    ps.setLong(6, project.getAuthorId());
    ps.setTimestamp(7, new Timestamp(project.getDate().getTime()));

    ps.executeUpdate();
    ResultSet rs = ps.getGeneratedKeys();
    Long projectId = null;
    if (rs.next()) {
        projectId = rs.getLong(1);
    }

    if (project.getParentId() > 0) {
        // Increasing the parents project subprojects_count var
        update("update projects set subprojects_count = subprojects_count+1 where id = :id", "id",
                project.getParentId());
    }

    return projectId;
}

From source file:com.wso2telco.dep.ratecardservice.dao.RateTaxDAO.java

public RateTaxDTO addRateTax(RateTaxDTO rateTax) throws BusinessException {

    Connection con = null;/* w w  w.  j a  v  a2s.c  om*/
    PreparedStatement ps = null;
    ResultSet rs = null;
    Integer rateTaxId = 0;

    try {

        con = DbUtils.getDbConnection(DataSourceNames.WSO2TELCO_RATE_DB);
        if (con == null) {

            log.error("unable to open " + DataSourceNames.WSO2TELCO_RATE_DB + " database connection");
            throw new BusinessException(ServiceError.SERVICE_ERROR_OCCURED);
        }

        StringBuilder query = new StringBuilder("insert into ");
        query.append(DatabaseTables.RATE_TAX.getTObject());
        query.append(" (rate_defid, taxid, createdby)");
        query.append(" values");
        query.append(" (?, ?, ?)");

        ps = con.prepareStatement(query.toString(), Statement.RETURN_GENERATED_KEYS);

        log.debug("sql query in addRateTax : " + ps);

        ps.setInt(1, rateTax.getRateDefinition().getRateDefId());
        ps.setInt(2, rateTax.getTax().getTaxId());
        ps.setString(3, rateTax.getCreatedBy());

        ps.executeUpdate();

        rs = ps.getGeneratedKeys();

        while (rs.next()) {

            rateTaxId = rs.getInt(1);
        }

        rateTax.setRateTaxId(rateTaxId);
    } catch (SQLException e) {

        log.error("database operation error in addRateTax : ", e);
        throw new BusinessException(ServiceError.SERVICE_ERROR_OCCURED);
    } catch (Exception e) {

        log.error("error in addRateTax : ", e);
        throw new BusinessException(ServiceError.SERVICE_ERROR_OCCURED);
    } finally {

        DbUtils.closeAllConnections(ps, con, rs);
    }

    return rateTax;
}

From source file:iddb.runtime.db.model.dao.impl.mysql.PenaltyDAOImpl.java

@Override
public void save(Penalty penalty) {
    String sql;//from ww  w . j  a va  2  s . c om
    if (penalty.getKey() == null) {
        sql = "insert into penalty (playerid, adminid, type, reason, duration, synced, active, created, updated, expires) values (?,?,?,?,?,?,?,?,?,?)";
    } else {
        sql = "update penalty set playerid = ?," + "adminid = ?," + "type = ?," + "reason = ?,"
                + "duration = ?," + "synced = ?," + "active = ?," + "created = ?," + "updated = ?,"
                + "expires = ? where id = ? limit 1";
    }
    Connection conn = null;
    try {
        conn = ConnectionFactory.getMasterConnection();
        PreparedStatement st = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
        st.setLong(1, penalty.getPlayer());
        if (penalty.getAdmin() != null)
            st.setLong(2, penalty.getAdmin());
        else
            st.setNull(2, Types.INTEGER);
        st.setInt(3, penalty.getType().intValue());
        if (penalty.getReason() != null)
            st.setString(4, penalty.getReason());
        else
            st.setNull(4, Types.VARCHAR);
        if (penalty.getDuration() == null)
            penalty.setDuration(0L);
        st.setLong(5, penalty.getDuration());
        st.setBoolean(6, penalty.getSynced());
        st.setBoolean(7, penalty.getActive());
        if (penalty.getCreated() == null)
            penalty.setCreated(new Date());
        if (penalty.getUpdated() == null)
            penalty.setUpdated(new Date());
        st.setTimestamp(8, new java.sql.Timestamp(penalty.getCreated().getTime()));
        st.setTimestamp(9, new java.sql.Timestamp(penalty.getUpdated().getTime()));
        st.setTimestamp(10, new java.sql.Timestamp(
                DateUtils.addMinutes(penalty.getCreated(), penalty.getDuration().intValue()).getTime()));
        if (penalty.getKey() != null)
            st.setLong(11, penalty.getKey());
        st.executeUpdate();
        if (penalty.getKey() == null) {
            ResultSet rs = st.getGeneratedKeys();
            if (rs != null && rs.next()) {
                penalty.setKey(rs.getLong(1));
            } else {
                logger.warn("Couldn't get id for penalty player id {}", penalty.getPlayer());
            }
        }
    } catch (SQLException e) {
        logger.error("Save: {}", e);
    } catch (IOException e) {
        logger.error("Save: {}", e);
    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
        }
    }
}

From source file:com.adanac.module.blog.dao.RecordDao.java

public Integer save(String username, String title, String record, String content) {
    return execute(new TransactionalOperation<Integer>() {
        @Override// w  w w. java2  s  . c  om
        public Integer doInConnection(Connection connection) {
            String sql = "insert into records (username,title,record,content,create_date) values (?,?,?,?,?)";
            try {
                PreparedStatement statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                statement.setString(1, username);
                statement.setString(2, title);
                statement.setString(3, record);
                statement.setString(4, content);
                statement.setTimestamp(5, new Timestamp(System.currentTimeMillis()));
                int result = statement.executeUpdate();
                if (result > 0) {
                    ResultSet keyResultSet = statement.getGeneratedKeys();
                    if (keyResultSet.next()) {
                        return keyResultSet.getInt(1);
                    }
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            return null;
        }
    });
}

From source file:com.orangeandbronze.jblubble.jdbc.JdbcBlobstoreService.java

@Override
public BlobKey createBlob(BlobstoreWriteCallback callback, String name, String contentType)
        throws IOException, BlobstoreException {
    try {/*from w  w w  .j  av a  2  s  .  c  om*/
        try (Connection connection = dataSource.getConnection();
                PreparedStatement ps = connection.prepareStatement(getInsertSql(),
                        Statement.RETURN_GENERATED_KEYS);) {
            ps.setString(1, name);
            ps.setString(2, contentType);
            Blob content = connection.createBlob();
            try {
                long size;
                String md5Hash = null;
                OutputStream out = new BufferedOutputStream(content.setBinaryStream(1L), getBufferSize());
                try {
                    CountingOutputStream countingOutputStream = new CountingOutputStream(out);
                    try {
                        MessageDigest md5;
                        try {
                            md5 = MessageDigest.getInstance(MD5_ALGORITHM_NAME);
                            try (DigestOutputStream digestOutputStream = new DigestOutputStream(
                                    countingOutputStream, md5)) {
                                size = callback.writeToOutputStream(digestOutputStream);
                                if (size == -1L) {
                                    size = countingOutputStream.getByteCount();
                                }
                                md5Hash = new String(encodeHex(md5.digest()));
                            }
                        } catch (NoSuchAlgorithmException e) {
                            throw new BlobstoreException(e);
                        }
                    } finally {
                        countingOutputStream.close();
                    }
                } finally {
                    out.close();
                }
                ps.setBlob(3, content);
                ps.setLong(4, size);
                ps.setTimestamp(5, new java.sql.Timestamp(new java.util.Date().getTime()));
                ps.setString(6, md5Hash);
                int rowCount = ps.executeUpdate();
                if (rowCount == 0) {
                    throw new BlobstoreException("Creating blob failed, no rows created.");
                }
                long generatedId = getGeneratedKey(ps);
                return new BlobKey(String.valueOf(generatedId));
            } finally {
                content.free();
            }
        }
    } catch (SQLException e) {
        throw new BlobstoreException("Error when creating blob", e);
    }
}

From source file:com.hs.mail.imap.dao.MySqlMessageDao.java

private long addPhysicalMessage(final MailMessage message) {
    final String sql = "INSERT INTO physmessage (size, internaldate, subject, sentdate, fromaddr) VALUES(?, ?, ?, ?, ?)";
    final MessageHeader header = message.getHeader();
    KeyHolder keyHolder = new GeneratedKeyHolder();
    getJdbcTemplate().update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
            PreparedStatement pstmt = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            pstmt.setLong(1, message.getSize()); // size
            pstmt.setTimestamp(2, new Timestamp(message.getInternalDate().getTime())); // internaldate
            pstmt.setString(3, header.getSubject()); // subject
            Date sent = header.getDate();
            pstmt.setTimestamp(4, (sent != null) ? new Timestamp(sent.getTime()) : null); // sentdate
            pstmt.setString(5, (header.getFrom() != null) ? header.getFrom().getDisplayString() : null); // fromaddr
            return pstmt;
        }/*from w ww  .j av a2s. co  m*/
    }, keyHolder);
    long physmessageid = keyHolder.getKey().longValue();
    message.setPhysMessageID(physmessageid);
    addHeader(physmessageid, header);
    return physmessageid;
}

From source file:com.wso2telco.dep.ratecardservice.dao.RateCategoryDAO.java

public RateCategoryDTO addRateCategory(RateCategoryDTO rateCategory) throws BusinessException {

    Connection con = null;/*from  www  .  j a va  2s . co m*/
    PreparedStatement ps = null;
    ResultSet rs = null;
    Integer rateCategoryId = 0;

    try {

        con = DbUtils.getDbConnection(DataSourceNames.WSO2TELCO_RATE_DB);
        if (con == null) {

            log.error("unable to open " + DataSourceNames.WSO2TELCO_RATE_DB + " database connection");
            throw new BusinessException(ServiceError.SERVICE_ERROR_OCCURED);
        }

        StringBuilder query = new StringBuilder("insert into ");
        query.append(DatabaseTables.RATE_CATEGORY.getTObject());
        query.append(" (rate_defid, parentcategoryid, childcategoryid, tariffid, createdby)");
        query.append(" values");
        query.append(" (?, ?, ?, ?, ?)");

        ps = con.prepareStatement(query.toString(), Statement.RETURN_GENERATED_KEYS);

        log.debug("sql query in addRateCategory : " + ps);

        ps.setInt(1, rateCategory.getRateDefinition().getRateDefId());
        ps.setInt(2, rateCategory.getCategory().getCategoryId());
        Integer subCategoryId = rateCategory.getSubCategory().getCategoryId();

        if (subCategoryId != null) {
            ps.setInt(3, subCategoryId);
        } else {
            ps.setNull(3, Types.INTEGER);
        }

        ps.setInt(4, rateCategory.getTariff().getTariffId());
        ps.setString(5, rateCategory.getCreatedBy());

        ps.executeUpdate();

        rs = ps.getGeneratedKeys();

        while (rs.next()) {

            rateCategoryId = rs.getInt(1);
        }

        rateCategory.setRateCategoryId(rateCategoryId);
    } catch (SQLException e) {

        log.error("database operation error in addRateCategory : ", e);
        throw new BusinessException(ServiceError.SERVICE_ERROR_OCCURED);
    } catch (Exception e) {

        log.error("error in addRateCategory : ", e);
        throw new BusinessException(ServiceError.SERVICE_ERROR_OCCURED);
    } finally {

        DbUtils.closeAllConnections(ps, con, rs);
    }

    return rateCategory;
}

From source file:com.javacodegags.waterflooding.model.FloodingImplemented.java

@Override
public int insert(final String name) {
    final String sql = "INSERT INTO flooding (name) VALUES (?);";
    KeyHolder holder = new GeneratedKeyHolder();
    jdbcTemplate.update(new PreparedStatementCreator() {

        @Override//ww w.j  a  v a2 s. c  om
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            ps.setString(1, name);
            return ps;
        }
    }, holder);
    return holder.getKey().intValue();
}

From source file:dao.MaterialDaoImplem.java

@Override
public int insertMaterial(Material material) {
    try (Connection connection = dataSource.getConnection()) {
        String query = ("INSERT INTO Material (name, weight, manufacturer,cost,quantity) values(?,?,?,?,?)");
        PreparedStatement stat = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
        stat.setString(1, material.getName());
        stat.setInt(2, material.getWeight());
        stat.setString(3, material.getManufacturer());
        stat.setInt(4, material.getCost());
        stat.setInt(5, material.getQuantity());
        stat.execute();//from  w  w  w .j av  a 2 s  . c  o m
        ResultSet res = stat.getGeneratedKeys();
        if (res.next()) {
            return res.getInt(1);
        } else {
            throw new RuntimeException("? ?    ");
        }
    } catch (Exception e) {
        throw new RuntimeException("Error:insertMaterial", e);
    }
}

From source file:org.wso2.carbon.identity.authorization.core.jdbc.dao.JDBCPermissionDAO.java

@Override
protected void insert(PreparedStatement stmt, ResultSet res, Connection connection)
        throws SQLException, UserStoreException {
    String sql = "INSERT INTO UM_PERMISSION (UM_RESOURCE_ID, UM_MODULE_ID, UM_TENANT_ID, UM_ACTION) VALUES(?,?,?,?) ";

    stmt = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
    byte count = 0;
    stmt.setString(++count, getResourceId());
    stmt.setInt(++count, getModuleId());
    stmt.setInt(++count, getTenantId());
    stmt.setString(++count, getAction());

    int resCount = stmt.executeUpdate();
    if (resCount == 0) {
        String error = "Insertion faild for the permission";
        log.error(error);/*from  w  ww  .j  a v  a 2 s  .  c  o m*/
        throw new UserStoreException(error);
    }
    res = stmt.getGeneratedKeys();
    if (res.next()) {
        setPermissionId(res.getInt(1));
    }

}