Example usage for org.springframework.jdbc.core PreparedStatementCreator PreparedStatementCreator

List of usage examples for org.springframework.jdbc.core PreparedStatementCreator PreparedStatementCreator

Introduction

In this page you can find the example usage for org.springframework.jdbc.core PreparedStatementCreator PreparedStatementCreator.

Prototype

PreparedStatementCreator

Source Link

Usage

From source file:com.skycloud.management.portal.admin.sysmanage.dao.impl.UserManageDaoImpl.java

@Override
public int saveSelfcaerUser(final TUserBO user) throws SQLException {
    KeyHolder keyHolder = new GeneratedKeyHolder();
    final String sql = "insert into T_SCS_USER(" + "ID,ACCOUNT,PWD," + "DEPT_ID,ROLE_ID,EMAIL,"
            + "POSITION,STATE," + "COMMENT,CHECK_CODE,IS_AUTO_APPROVE,CREATOR_USER_ID,"
            + "CREATE_DT,LASTUPDATE_DT,COMP_ID,MOBILE) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
    try {//w w w. ja va 2 s  . co  m
        this.getJdbcTemplate().update(new PreparedStatementCreator() {
            int i = 1;

            @Override
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                ps.setInt(i++, user.getId());
                ps.setString(i++, user.getAccount());
                ps.setString(i++, user.getPwd());
                //               ps.setString(i++, user.getName());
                ps.setInt(i++, user.getDeptId());
                ps.setInt(i++, user.getRoleId());
                ps.setString(i++, user.getEmail());
                ps.setString(i++, user.getPosition());
                ps.setInt(i++, user.getState());
                ps.setString(i++, user.getComment());
                ps.setString(i++, user.getCheckCode());
                ps.setInt(i++, user.getIsAutoApprove());
                ps.setInt(i++, user.getCreatorUserId());
                ps.setTimestamp(i++, new Timestamp(user.getCreateDt().getTime()));
                //update by CQ
                ps.setTimestamp(i++, new Timestamp(user.getLastupdateDt().getTime()));
                ps.setInt(i++, user.getCompId());
                ps.setString(i++, user.getMobile());
                return ps;
            }
        }, keyHolder);
    } catch (Exception e) {
        throw new SQLException("??" + user.getComment() + " ID"
                + user.getCreatorUserId() + " " + user.getCreateDt() + " "
                + e.getMessage());
    }
    return keyHolder.getKey().intValue();
}

From source file:org.pegadi.server.publication.PublicationServerImpl.java

/**
 * Saves or updates a publication in persistent storage. If the ID is less than or equals to zero,
 * it is created, else it is updated./*  ww w .j av  a 2 s. com*/
 *
 * @return ID of created publication
 */
public int saveOrUpdatePublication(final Publication pub) {
    if (pub.getId() > 0) {
        template.update(
                "UPDATE Publication SET name=?, releasedate=?, printdate=?, deadlineText=?, description=?, number=? WHERE ID=?",
                pub.getName(),
                new java.sql.Date(pub.getReleaseDate() != null ? pub.getReleaseDate().getTime()
                        : new java.util.Date().getTime()),
                new java.sql.Date(pub.getPrintDate() != null ? pub.getPrintDate().getTime()
                        : new java.util.Date().getTime()),
                new java.sql.Date(pub.getDeadlineText() != null ? pub.getDeadlineText().getTime()
                        : new java.util.Date().getTime()),
                pub.getDescription(), pub.getNumber(), pub.getId());
    } else {
        final String insertSql = "INSERT INTO Publication (name, releasedate, printdate, deadlineText, description, number) VALUES (?, ?, ?, ?, ?, ?)";
        KeyHolder keyHolder = new GeneratedKeyHolder();

        template.update(new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement stmt = connection.prepareStatement(insertSql, new String[] { "ID" });
                stmt.setString(1, pub.getName());
                stmt.setDate(2, new java.sql.Date(pub.getReleaseDate() != null ? pub.getReleaseDate().getTime()
                        : new java.util.Date().getTime()));
                stmt.setDate(3, new java.sql.Date(pub.getPrintDate() != null ? pub.getPrintDate().getTime()
                        : new java.util.Date().getTime()));
                stmt.setDate(4,
                        new java.sql.Date(pub.getDeadlineText() != null ? pub.getDeadlineText().getTime()
                                : new java.util.Date().getTime()));
                stmt.setString(5, pub.getDescription() != null ? pub.getDescription() : "");

                Calendar cal = Calendar.getInstance();
                cal.setTime(pub.getReleaseDate() != null ? pub.getReleaseDate() : new java.util.Date());
                stmt.setInt(6, getPublicationsByYear(cal.get(Calendar.YEAR)).size() + 1);

                return stmt;
            }
        }, keyHolder);
        pub.setId(keyHolder.getKey().intValue());
    }
    return pub.getId();
}

From source file:net.freechoice.dao.impl.Dao_Post.java

@Trigger(action = "update search_vector after the update of content")
@Override/*  www  .  j a  va2 s  .co  m*/
public void updateContentOf(final int id, final String content) {

    getJdbcTemplate().update(new PreparedStatementCreator() {

        @Override
        public PreparedStatement createPreparedStatement(Connection arg0) throws SQLException {
            PreparedStatement ps = arg0.prepareStatement("update fc_post set content = ? " + "where id = ?;"
                    + "update fc_post set search_vector = to_tsvector(content) " + "where id = ?");
            ps.setString(1, content);
            ps.setInt(2, id);
            ps.setInt(3, id);
            return ps;
        }
    });
}

From source file:net.solarnetwork.node.dao.jdbc.AbstractJdbcDao.java

/**
 * Insert a new domain object./*from  w ww .j a  va  2s . co  m*/
 * 
 * @param obj
 *        the domain object to insert
 * @param sqlInsert
 *        the SQL to persist the object with
 */
protected void insertDomainObject(final T obj, final String sqlInsert) {
    getJdbcTemplate().update(new PreparedStatementCreator() {

        @Override
        public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
            PreparedStatement ps = con.prepareStatement(sqlInsert);
            setStoreStatementValues(obj, ps);
            return ps;
        }
    });
}

From source file:net.duckling.ddl.service.resource.dao.ResourceDAOImpl.java

@Override
public synchronized int create(final Resource res) {
    GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
    this.getJdbcTemplate().update(new PreparedStatementCreator() {
        @Override/*w  ww.  ja v a2  s. com*/
        public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
            PreparedStatement ps = null;
            ps = conn.prepareStatement(SQL_CREATE, PreparedStatement.RETURN_GENERATED_KEYS);
            int i = 0;
            //tid,item_type,title,creator,creator_name,create_time,last_editor,last_editor_name,last_edit_time,last_version,tags,marked_users,bid
            ps.setInt(++i, res.getTid());
            ps.setString(++i, res.getItemType());
            ps.setString(++i, res.getTitle());
            ps.setString(++i, res.getCreator());
            ps.setTimestamp(++i, new Timestamp(res.getCreateTime().getTime()));
            ps.setString(++i, res.getLastEditor());
            ps.setString(++i, res.getLastEditorName());
            ps.setTimestamp(++i, new Timestamp(res.getLastEditTime().getTime()));
            ps.setInt(++i, res.getLastVersion());
            ps.setString(++i, JsonUtil.getJSONString(res.getTagMap()));
            String fileType = (res.getFileType() != null) ? res.getFileType().toLowerCase() : res.getFileType();
            ps.setString(++i, fileType);
            ps.setObject(++i, res.getMarkedUserSet());
            ps.setInt(++i, res.getBid());
            ps.setInt(++i, res.getOrderType());
            ps.setString(++i, res.getStatus());
            ps.setLong(++i, res.getSize());
            ps.setBoolean(++i, res.isShared());
            return ps;
        }

    }, keyHolder);
    Number key = keyHolder.getKey();
    return (key == null) ? -1 : key.intValue();
}

From source file:net.bhira.sample.api.dao.CompanyDaoImpl.java

/**
 * @see net.bhira.sample.api.dao.CompanyDao#save(net.bhira.sample.model.Company)
 *//*from   ww w  .  j  a  v  a 2s .c  om*/
@Override
public void save(Company company)
        throws ObjectNotFoundException, InvalidObjectException, InvalidReferenceException {
    if (company == null) {
        throw new InvalidObjectException("Company object is null.");
    }

    company.initForSave();
    company.validate();
    boolean isNew = company.isNew();
    int count = 0;

    if (isNew) {
        // for new company, construct SQL insert statement
        KeyHolder keyHolder = new GeneratedKeyHolder();
        count = jdbcTemplate.update(new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement pstmt = connection.prepareStatement(SQL_INSERT,
                        Statement.RETURN_GENERATED_KEYS);
                pstmt.setString(1, company.getName());
                pstmt.setString(2, company.getIndustry());
                pstmt.setString(3, company.getBillingAddress());
                pstmt.setString(4, company.getShippingAddress());
                pstmt.setTimestamp(5, new Timestamp(company.getCreated().getTime()));
                pstmt.setTimestamp(6, new Timestamp(company.getModified().getTime()));
                pstmt.setString(7, company.getCreatedBy());
                pstmt.setString(8, company.getModifiedBy());
                return pstmt;
            }
        }, keyHolder);

        // fetch the newly created auto-increment ID
        company.setId(keyHolder.getKey().longValue());
        LOG.debug("inserted company, count = {}, id = {}", count, company.getId());

    } else {
        // for existing company, construct SQL update statement
        Object[] args = new Object[] { company.getName(), company.getIndustry(), company.getBillingAddress(),
                company.getShippingAddress(), company.getModified(), company.getModifiedBy(), company.getId() };
        count = jdbcTemplate.update(SQL_UPDATE, args);
        LOG.debug("updated company, count = {}, id = {}", count, company.getId());
    }

    // if insert/update has 0 count value, then throw exception
    if (count <= 0) {
        throw new ObjectNotFoundException("Company with ID " + company.getId() + " was not found.");
    }

    // update dependent entries, as needed
    if (isNew) {

        // for new model if there is contact info, save it to contact info table and then
        // add entry in relationship table
        if (company.getContactInfo() != null) {
            contactInfoDao.save(company.getContactInfo());
            Object[] args = new Object[] { company.getId(), company.getContactInfo().getId() };
            jdbcTemplate.update(SQL_CINFO_REL_INSERT, args);
        }

    } else {
        // for existing model, fetch contact info ID from relationship table
        List<Long> cinfoIds = jdbcTemplate.queryForList(SQL_CINFO_REL_LOAD, Long.class,
                new Object[] { company.getId() });
        Long cinfoId = (cinfoIds != null && !cinfoIds.isEmpty()) ? cinfoIds.get(0) : null;

        if (company.getContactInfo() == null) {
            // clean up old contact info entry, if needed
            if (cinfoId != null) {
                jdbcTemplate.update(SQL_CINFO_REL_DELETE, new Object[] { company.getId() });
                contactInfoDao.delete(cinfoId);
            }

        } else {
            // insert/update contact info entry
            if (cinfoId != null) {
                company.getContactInfo().setId(cinfoId);
                contactInfoDao.save(company.getContactInfo());
            } else {
                contactInfoDao.save(company.getContactInfo());
                Object[] args = new Object[] { company.getId(), company.getContactInfo().getId() };
                jdbcTemplate.update(SQL_CINFO_REL_INSERT, args);
            }
        }
    }
}

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

@Override
public int insertCriteria(int id) {
    final String sql = "INSERT INTO criteria (foreign_to_therm,formula,weight_factor,criteria_value) VALUES ("
            + id + ",'','0.1','0.1');";
    KeyHolder holder = new GeneratedKeyHolder();
    jdbcTemplate.update(new PreparedStatementCreator() {

        @Override//  w w  w .j  a  va  2  s  . c o m
        public PreparedStatement createPreparedStatement(Connection cnctn) throws SQLException {
            PreparedStatement ps = cnctn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            return ps;
        }
    }, holder);
    this.setDefaultParams(holder.getKey().intValue());
    return holder.getKey().intValue();
}

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

public long addAlias(final Alias alias) {
    final String sql = "INSERT INTO alias (alias, deliver_to) VALUES(?, ?)";
    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.setString(1, alias.getAlias());
            pstmt.setLong(2, alias.getDeliverTo());
            return pstmt;
        }/*  ww w .  ja  va 2s  .co m*/
    }, keyHolder);
    long id = keyHolder.getKey().longValue();
    alias.setID(id);
    return id;
}

From source file:net.freechoice.dao.impl.DaoPost.java

@Override
public List<FC_Post> getDraftsOfAuthor(final int userId, final int length, final Timestamp offset,
        final int limit) {

    return getJdbcTemplate().query(new PreparedStatementCreator() {

        @Override/*w  w  w .  ja  v a  2s  .  c o  m*/
        public PreparedStatement createPreparedStatement(Connection arg0) throws SQLException {
            PreparedStatement ps = arg0.prepareStatement(
                    select(length) + " where id_author = ? and time_posted < ? " + TIME_DESCEND + " limit ?");
            ps.setInt(1, userId);
            ps.setTimestamp(1, offset);
            ps.setInt(3, limit);
            return ps;
        }
    }, mapper);
}

From source file:com.ineunet.knife.persist.Jdbc.java

/**
 * Column Name of Primary key must be 'id'.
 * //w w w  . j  av  a 2s. c  o m
 * @param sql
 * @param values
 * @return id
 */
public <X> Long createIncrement(final String sql, final Object... values) {
    KeyHolder keyHolder = new GeneratedKeyHolder();
    jdbcTemplate.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
            PreparedStatement ps = conn.prepareStatement(sql, new String[] { "id" });
            for (int i = 0; i < values.length; i++)
                ps.setObject(i + 1, values[i]);
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().longValue();
}