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

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

Introduction

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

Prototype

ConnectionCallback

Source Link

Usage

From source file:gov.nih.nci.cabig.caaers.datamigrator.CaaersDataMigratorTemplate.java

private String getDBName() {
    if (DB_PRODUCT_VERSION == null) {
        DB_PRODUCT_VERSION = (String) getJdbcTemplate().execute(new ConnectionCallback() {
            public Object doInConnection(Connection con) throws SQLException, DataAccessException {
                return con.getMetaData().getDatabaseProductVersion();
            }/*w  w w .  ja v a 2 s .c  o  m*/
        });
    }

    return DB_PRODUCT_VERSION;
}

From source file:org.wte4j.examples.showcase.server.config.DatabaseConfigTest.java

@Test
public void databaseIsIntializedTest() {
    JdbcTemplate template = new JdbcTemplate(ds);
    Set<String> wte4jTables = template.execute(new ConnectionCallback<Set<String>>() {

        @Override//from  w ww .j  a  v a 2  s  . co m
        public Set<String> doInConnection(Connection con) throws SQLException, DataAccessException {
            Set<String> tableNames = new HashSet<String>();
            ResultSet tableRs = con.getMetaData().getTables(null, null, null, new String[] { "TABLE" });
            try {
                while (tableRs.next()) {
                    tableNames.add(tableRs.getString("TABLE_NAME").toLowerCase());
                }
            } finally {
                tableRs.close();
            }
            return tableNames;
        }
    });
    assertEquals(6, wte4jTables.size());
    assertTrue(wte4jTables.contains("person"));
    assertTrue(wte4jTables.contains("purchase_order"));
    assertTrue(wte4jTables.contains("wte4j_template"));
    assertTrue(wte4jTables.contains("wte4j_template_properties"));
    assertTrue(wte4jTables.contains("wte4j_gen"));
    assertTrue(wte4jTables.contains("wte4j_template_content_mapping"));
}

From source file:org.brickhouse.impl.DatabaseImpl.java

protected boolean tableExists(final String name) {
    return jt.execute(new ConnectionCallback<Boolean>() {
        @Override/*w w  w  .j a va  2 s  . c  o m*/
        public Boolean doInConnection(Connection con) throws SQLException, DataAccessException {
            return con.getMetaData().getTables(null, null, name.toLowerCase(), null).next();
        }
    });
}

From source file:com.googlecode.flyway.core.dbsupport.mysql.MySQLDbSupport.java

public String getCurrentSchema() {
    return (String) jdbcTemplate.execute(new ConnectionCallback() {
        public String doInConnection(Connection connection) throws SQLException, DataAccessException {
            return connection.getCatalog();
        }/*  w ww.ja  va  2  s  .com*/
    });
}

From source file:com.alibaba.otter.canal.example.db.dialect.AbstractDbDialect.java

public AbstractDbDialect(final JdbcTemplate jdbcTemplate, LobHandler lobHandler) {
    this.jdbcTemplate = jdbcTemplate;
    this.lobHandler = lobHandler;
    // ?transction
    this.transactionTemplate = new TransactionTemplate();
    transactionTemplate.setTransactionManager(new DataSourceTransactionManager(jdbcTemplate.getDataSource()));
    transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);

    // ??//from  ww  w  .  jav a 2  s .c  om
    jdbcTemplate.execute(new ConnectionCallback() {

        public Object doInConnection(Connection c) throws SQLException, DataAccessException {
            DatabaseMetaData meta = c.getMetaData();
            databaseName = meta.getDatabaseProductName();
            databaseMajorVersion = meta.getDatabaseMajorVersion();
            databaseMinorVersion = meta.getDatabaseMinorVersion();

            return null;
        }
    });

    initTables(jdbcTemplate);
}

From source file:com.googlecode.flyway.core.dbsupport.postgresql.PostgreSQLDbSupport.java

public boolean tableExists(final String schema, final String table) {
    return (Boolean) jdbcTemplate.execute(new ConnectionCallback() {
        public Boolean doInConnection(Connection connection) throws SQLException, DataAccessException {
            ResultSet resultSet = connection.getMetaData().getTables(null, schema.toLowerCase(),
                    table.toLowerCase(), new String[] { "TABLE" });
            return resultSet.next();
        }// w  w w .j a va2  s. c o m
    });
}

From source file:de.whs.poodle.repositories.McQuestionRepository.java

public int save(McQuestion question) {

    if (question.getText().trim().isEmpty())
        throw new BadRequestException("noExerciseTextSpecified");

    for (Answer a : question.getAnswers()) {
        if (a.getText().trim().isEmpty())
            throw new BadRequestException("emptyAnswer");
    }//  ww  w . ja  v  a  2  s  .c  o  m

    return jdbc.execute(new ConnectionCallback<Integer>() {

        @Override
        public Integer doInConnection(Connection con) throws SQLException, DataAccessException {
            try (PreparedStatement questionPs = con.prepareStatement(
                    "INSERT INTO mc_question(course_id,text,has_multiple_correct_answers,changed_by_id,root_id,visibility,comment) VALUES(?,?,?,?,?,?::exercise_visibility,?)",
                    PreparedStatement.RETURN_GENERATED_KEYS);

                    PreparedStatement answersPs = con.prepareStatement(
                            "INSERT INTO mc_question_to_answer(mc_question_id,correct,text) VALUES(?,?,?)");

                    PreparedStatement tagsPs = con.prepareStatement(
                            "INSERT INTO mc_question_to_tag(mc_question_id,tag_id) VALUES(?,?)");

                    /* If this is a new revision, this updates the revision in existing worksheets.
                     * Note that we only do this if no statistics exist yet, because we would screw
                     * those up otherwise (the answer IDs in mc_chosen_answer wouldn't match the
                     * question revision anymore). */
                    PreparedStatement updateWorksheetsPs = con
                            .prepareStatement("UPDATE mc_worksheet_to_question wtq SET mc_question_id = ? "
                                    + "WHERE mc_question_id IN (SELECT id FROM mc_question WHERE root_id = ?) "
                                    + "AND NOT EXISTS (SELECT 1 FROM mc_statistic WHERE mc_worksheet_to_question_id = wtq.id)");) {
                con.setAutoCommit(false);

                // inner try for rollback
                try {
                    // exercise
                    questionPs.setInt(1, question.getCourseId());
                    questionPs.setString(2, question.getText());
                    questionPs.setBoolean(3, question.isMultipleCorrectAnswers());

                    questionPs.setInt(4, question.getChangedBy().getId());

                    /*
                     * The root id is always the ID of the first revision. If this
                     * is a new exercise, this ID obviously doesn't exist yet. We set
                     * NULL in this case, but a trigger in the DB will automatically
                     * set the root_id to the generated id.
                     */
                    if (question.getRootId() == 0)
                        questionPs.setNull(5, Types.INTEGER);
                    else
                        questionPs.setInt(5, question.getRootId());

                    questionPs.setString(6, question.getVisibility().toString());

                    questionPs.setString(7, question.getComment());

                    questionPs.executeUpdate();

                    ResultSet genRs = questionPs.getGeneratedKeys();
                    genRs.next();
                    int questionId = genRs.getInt(1);

                    // answers
                    answersPs.setInt(1, questionId);

                    for (Answer a : question.getAnswers()) {
                        answersPs.setBoolean(2, a.isCorrect());
                        answersPs.setString(3, a.getText());
                        answersPs.addBatch();
                    }

                    answersPs.executeBatch();

                    // tag relations
                    tagsPs.setInt(1, questionId);

                    for (Tag t : question.getTags()) {
                        tagsPs.setInt(2, t.getId());
                        tagsPs.addBatch();
                    }

                    tagsPs.executeBatch();

                    // if this is new revision, update it in the worksheets
                    if (question.getRootId() != 0) {
                        updateWorksheetsPs.setInt(1, questionId);
                        updateWorksheetsPs.setInt(2, question.getRootId());
                        updateWorksheetsPs.executeUpdate();
                    }

                    con.commit();

                    return questionId;

                } catch (SQLException e) {
                    con.rollback();
                    throw e;
                } finally {
                    con.setAutoCommit(true);
                }
            }
        }
    });
}

From source file:de.whs.poodle.repositories.ExerciseRepository.java

public void save(Exercise exercise) {
    if (exercise.getTitle().trim().isEmpty())
        throw new BadRequestException("noTitleSpecified");
    if (exercise.getText().trim().isEmpty())
        throw new BadRequestException("noExerciseTextSpecified");

    jdbc.execute(new ConnectionCallback<Void>() {

        @Override//from   w w  w  .  ja  va2  s . c om
        public Void doInConnection(Connection con) throws SQLException, DataAccessException {
            try (CallableStatement exercisePs = con
                    .prepareCall("{ ? = CALL create_exercise(?,?,?::exercise_visibility,?,?,?,?,?,?,?,?,?) }");

                    PreparedStatement tagsPs = con
                            .prepareStatement("INSERT INTO exercise_to_tag(exercise_id,tag_id) VALUES(?,?)");) {
                con.setAutoCommit(false);

                // inner try for rollback
                try {
                    // create exercise
                    exercisePs.registerOutParameter(1, Types.INTEGER); // new_id

                    exercisePs.setString(2, exercise.getText());

                    /*
                     * The root id is always the ID of the first revision. If this
                     * is a new exercise, this ID obviously doesn't exist yet. We set
                     * NULL in this case, but a trigger in the DB will automatically
                     * set the root_id to the generated id.
                     */
                    if (exercise.getRootId() == 0)
                        exercisePs.setNull(3, Types.INTEGER);
                    else
                        exercisePs.setInt(3, exercise.getRootId());

                    exercisePs.setString(4, exercise.getVisibility().toString());
                    exercisePs.setString(5, exercise.getTitle());
                    exercisePs.setInt(6, exercise.getChangedBy().getId());
                    exercisePs.setString(7, exercise.getHint1());
                    exercisePs.setString(8, exercise.getHint2());

                    // sample solution
                    SampleSolutionType sampleSolutionType = exercise.getSampleSolutionType();

                    if (sampleSolutionType == SampleSolutionType.NONE) {
                        exercisePs.setNull(9, Types.INTEGER);
                        exercisePs.setNull(10, Types.VARCHAR);
                    } else if (sampleSolutionType == SampleSolutionType.FILE) {
                        exercisePs.setInt(9, exercise.getSampleSolution().getFile().getId());
                        exercisePs.setNull(10, Types.VARCHAR);
                    } else { // must be text
                        exercisePs.setNull(9, Types.INTEGER);
                        exercisePs.setString(10, exercise.getSampleSolution().getText());
                    }

                    // attachments
                    List<Integer> attachmentIds = exercise.getAttachments().stream().map(a -> a.getId())
                            .collect(Collectors.toList());

                    Array anhaengeIdsArray = con.createArrayOf("int4", attachmentIds.toArray());
                    exercisePs.setArray(11, anhaengeIdsArray);

                    exercisePs.setInt(12, exercise.getCourseId());

                    exercisePs.setString(13, exercise.getComment());

                    exercisePs.executeUpdate();

                    /* Set the generated ID so the calling function can read it. */
                    exercise.setId(exercisePs.getInt(1));

                    // create relation to tags
                    tagsPs.setInt(1, exercise.getId());

                    for (Tag t : exercise.getTags()) {
                        tagsPs.setInt(2, t.getId());
                        tagsPs.addBatch();
                    }

                    tagsPs.executeBatch();

                    con.commit();
                } catch (SQLException e) {
                    con.rollback();
                    throw e;
                } finally {
                    con.setAutoCommit(true);
                }
            }

            return null;
        }
    });
}