Example usage for org.springframework.jdbc.core JdbcTemplate update

List of usage examples for org.springframework.jdbc.core JdbcTemplate update

Introduction

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

Prototype

@Override
    public int update(PreparedStatementCreator psc) throws DataAccessException 

Source Link

Usage

From source file:com.googlecode.flyway.core.migration.MigrationTestCase.java

/**
 * Check if meta table has no current migration (manually edited).
 *//* www. j  a va  2  s.c om*/
@Test(expected = FlywayException.class)
public void checkForInvalidMetatable() throws FlywayException {
    flyway.setBaseDir(BASEDIR);
    flyway.migrate();

    JdbcTemplate jdbcTemplate = new JdbcTemplate(migrationDataSource);
    DbSupport dbSupport = getDbSupport(jdbcTemplate);
    jdbcTemplate.update("UPDATE schema_version SET current_version = " + dbSupport.getBooleanFalse()
            + " where current_version = " + dbSupport.getBooleanTrue());
    flyway.migrate();
}

From source file:data.DefaultExchanger.java

public void importData(String dbName, JsonParser parser, JdbcTemplate jdbcTemplate) throws IOException {
    PlatformTransactionManager tm = new DataSourceTransactionManager(jdbcTemplate.getDataSource());
    TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());

    try {/*  w ww.  ja v a  2s  . c o m*/
        if (dbName.equals("MySQL")) {
            jdbcTemplate.update("SET FOREIGN_KEY_CHECKS = 0");
            jdbcTemplate.update("SET NAMES \'utf8mb4\'");
        }

        final Configuration config = Configuration.root();
        int batchSize = config.getInt(DATA_BATCH_SIZE_KEY, DEFAULT_BATCH_SIZE);
        if (parser.nextToken() != JsonToken.END_OBJECT) {
            String fieldName = parser.getCurrentName();
            play.Logger.debug("importing {}", fieldName);
            if (fieldName.equalsIgnoreCase(getTable())) {
                truncateTable(jdbcTemplate);
                JsonToken current = parser.nextToken();
                if (current == JsonToken.START_ARRAY) {
                    importDataFromArray(parser, jdbcTemplate, batchSize);
                    importSequence(dbName, parser, jdbcTemplate);
                } else {
                    play.Logger.info("Error: records should be an array: skipping.");
                    parser.skipChildren();
                }
            }
        }
        tm.commit(ts);
    } catch (Exception e) {
        e.printStackTrace();
        tm.rollback(ts);
    } finally {
        if (dbName.equals("MySQL")) {
            jdbcTemplate.update("SET FOREIGN_KEY_CHECKS = 1");
        }
    }
}

From source file:db.migration.V2017_08_27_14_00__Import_Images_Into_Db.java

@Override
public void migrate(JdbcTemplate jdbcTemplate) throws Exception {
    LOG.info("Importing images into db");
    List<ImageObject> images = jdbcTemplate.query(
            "select `" + FIELD_ID + "`, `" + FIELD_FILE_PATH + "` from `" + TABLE_NAME + "`",
            new ImageObjectRowMapper<>());
    for (ImageObject entry : images) {
        try {/*  w ww. j  a va 2  s  .  c om*/
            File file = new File(entry.getFilePath());
            byte[] data = IOUtils.toByteArray(new FileInputStream(file));
            if (data != null) {
                ImageCategory category = getCategory(entry.getFilePath());
                jdbcTemplate.update(connection -> {
                    PreparedStatement ps = connection.prepareStatement(
                            String.format("update `%s` set `%s` = ?, `%s` = ?, `%s` = ? where `%s` = ?",
                                    TABLE_NAME, FIELD_CONTENT_LENGTH, FIELD_CONTENT, FIELD_CATEGORY, FIELD_ID),
                            new String[] { FIELD_CONTENT });
                    ps.setLong(1, 0L + data.length);
                    ps.setBytes(2, data);
                    ps.setString(3, category.name());
                    ps.setLong(4, entry.getId());
                    return ps;
                });
            }
        } catch (Exception e) {
            LOG.error(String.format("Unable to import file %s: %s", entry.getFilePath(), e.getMessage()));
        }
    }
    LOG.info("Done importing images into db");
}

From source file:com.px100systems.data.plugin.persistence.jdbc.Storage.java

protected void create(final boolean lastSavedStorage) {
    connection.write(new JdbcCallback<Void>() {
        @Override/*from   w ww  . jav  a2 s  . c  o  m*/
        public Void transaction(JdbcTemplate jdbc) {
            jdbc.execute("CREATE TABLE " + table
                    + " (pk_id BIGINT AUTO_INCREMENT, unit_name VARCHAR(50), generator_name VARCHAR(50), class_name VARCHAR(100), id BIGINT, block_number INT, data_size INT, data "
                    + binaryType + "(" + blockSize + ")," + "  PRIMARY KEY (pk_id))");
            jdbc.execute("CREATE INDEX " + table + "_index0 ON " + table + " (unit_name, id)");

            if (lastSavedStorage) {
                jdbc.execute(
                        "CREATE TABLE last_saved (pk_id BIGINT NOT NULL, save_time BIGINT, PRIMARY KEY (pk_id))");
                jdbc.update("INSERT INTO last_saved (pk_id, save_time) VALUES (0, NULL)");
            }

            return null;
        }
    });
}

From source file:com.emc.ecs.sync.EndToEndTest.java

protected void verifyDb(TestObjectSource testSource, boolean truncateDb) {
    SingleConnectionDataSource ds = new SingleConnectionDataSource();
    ds.setUrl(SqliteDbService.JDBC_URL_BASE + dbFile.getPath());
    ds.setSuppressClose(true);//  w  w w . j a va  2  s .  co  m
    JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);

    long totalCount = verifyDbObjects(jdbcTemplate, testSource.getObjects());
    try {
        SqlRowSet rowSet = jdbcTemplate.queryForRowSet("SELECT count(source_id) FROM "
                + DbService.DEFAULT_OBJECTS_TABLE_NAME + " WHERE target_id != ''");
        Assert.assertTrue(rowSet.next());
        Assert.assertEquals(totalCount, rowSet.getLong(1));
        if (truncateDb)
            jdbcTemplate.update("DELETE FROM " + DbService.DEFAULT_OBJECTS_TABLE_NAME);
    } finally {
        try {
            ds.destroy();
        } catch (Throwable t) {
            log.warn("could not close datasource", t);
        }
    }
}

From source file:annis.dao.SpringAnnisDao.java

@Override
public void modifySqlSession(JdbcTemplate jdbcTemplate, QueryData queryData) {
    if (timeout > 0) {
        jdbcTemplate.update("SET statement_timeout TO " + timeout);
    }//  w  w w .  j  av a  2s  .  c om
}

From source file:de.uhh.l2g.dao.VideoDao.java

/**
 * Delete all.//from  w  ww  . ja  va  2 s .c  o m
 */
public void deleteAll() {

    JdbcTemplate delete = new JdbcTemplate(this.getDataSource());
    delete.update("DELETE from video");
    delete.update("DELETE from video_facility");
}

From source file:de.uhh.l2g.dao.VideoDao.java

/**
 * Creates the last video list.//  w  w w. j  a  v a 2 s.  c om
 *
 * @param start the start
 * @param ende the ende
 * @param facilityId the facility id
 * @param tree the tree
 */
public void createLastVideoList(int start, int ende, int facilityId, String tree) {
    List<Video> vlist = this.getLatestVideos(start, ende, facilityId, tree);
    //refresh the whole video list in the table
    JdbcTemplate jq = new JdbcTemplate(this.getDataSource());
    jq.update("DELETE FROM lastvideolist");
    ListIterator<Video> vIt = vlist.listIterator();
    while (vIt.hasNext()) {
        Video v = vIt.next();
        //save videos in table
        jq.update("INSERT INTO lastvideolist (videoId) VALUES(?)", new Object[] { v.getId() });
    }
}

From source file:de.uhh.l2g.dao.VideoDao.java

/**
 * Creates the popular video list.//from ww w .  ja  va 2  s .  c  o  m
 */
@SuppressWarnings("unchecked")
public void createPopularVideoList() {
    List<Video> returnList = new ArrayList<Video>();
    JdbcTemplate jdbst = new JdbcTemplate(this.getDataSource());
    String sqlquery = "SELECT v.id, v.title, v.tags, v.lectureseriesId, v.ownerId, v.producerId, v.containerFormat, v.filename, v.resolution, v.duration, v.hostId, v.textId, v.filesize, v.generationDate, v.openAccess, v.downloadLink, v.metadataId, v.surl, v.hits, v.uploadDate, v.permittedToSegment, v.facilityId, v.citation2go FROM video v WHERE v.openAccess=1 AND v.hits > 20 ORDER BY hits DESC ";
    returnList = jdbst.query(sqlquery, new VideoRowMapper());

    JdbcTemplate delete = new JdbcTemplate(this.getDataSource());
    delete.update("DELETE FROM videohitlist");

    Calendar calendar = new GregorianCalendar();
    calendar.setTimeZone(TimeZone.getTimeZone("CET"));
    long msnow = calendar.getTimeInMillis();

    Date d1 = new Date();
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd_HH-mm");

    for (Video v : returnList) {
        try {
            d1 = df.parse(v.getGenerationDate());
            long ms1 = d1.getTime();
            int hits = v.getHits();
            long timeinms = msnow - ms1;

            // Durschnittswerte berechnen

            //Berechne alter des Videos in...
            long days = timeinms / (1000 * 60 * 60 * 24); //...Tagen
            long week = timeinms / (1000 * 60 * 60 * 24 * 7); //...Wochen
            long month = timeinms / 2628000000l; //....Monaten
            long year = timeinms / (2628000000l * 12l); //....Jahren

            //Berechne die Hits pro...
            int clicksperday = calcHitsPro(days, hits);
            int clicksperweek = calcHitsPro(week, hits);
            int clickspermonth = calcHitsPro(month, hits);
            int clicksperyear = calcHitsPro(year, hits);

            createOneHit(v.getId(), clicksperday, clicksperweek, clickspermonth, clicksperyear);
        } catch (ParseException e) {
            System.out.println("Simple Date Parsen Error!!");
        }
    }

}

From source file:ca.nrc.cadc.vos.server.NodeDAOTest.java

@Before
public void setup() throws Exception {
    JdbcTemplate jdbc = new JdbcTemplate(dataSource);
    jdbc.update("delete from " + nodeSchema.propertyTable);
    jdbc.update("delete from " + nodeSchema.nodeTable);

    ContainerNode root = (ContainerNode) nodeDAO.getPath(HOME_CONTAINER);
    if (root == null) {
        VOSURI vos = new VOSURI(new URI("vos", VOS_AUTHORITY, "/" + HOME_CONTAINER, null, null));
        root = new ContainerNode(vos);
        root.getProperties().add(new NodeProperty(VOS.PROPERTY_URI_CREATOR, NODE_OWNER));
        root = (ContainerNode) nodeDAO.put(root, owner);
        log.debug("created base node: " + root.getUri());
    } else/*from ww w.  ja  v  a2s.  c om*/
        log.debug("found base node: " + root.getUri());

    ContainerNode deleted = (ContainerNode) nodeDAO.getPath(DELETED_NODES);
    if (deleted == null) {
        VOSURI vos = new VOSURI(new URI("vos", VOS_AUTHORITY, "/" + DELETED_NODES, null, null));
        deleted = new ContainerNode(vos);
        deleted.getProperties().add(new NodeProperty(VOS.PROPERTY_URI_CREATOR, DELETED_OWNER));
        deleted = (ContainerNode) nodeDAO.put(deleted, owner);
        log.debug("created base node: " + deleted);
    } else
        log.debug("found deleted node: " + deleted.getUri());
}