List of usage examples for org.springframework.jdbc.core JdbcTemplate execute
@Override public void execute(final String sql) throws DataAccessException
From source file:org.projectforge.database.DatabaseUpdateDao.java
/** * Creates the given data base index if not already exists. * @param name/* w w w . j av a 2 s.c o m*/ * @param table * @param attributes * @return true, if the index was created, false if an error has occured or the index already exists. */ public boolean createIndex(final String name, final String table, final String attributes) { accessCheck(true); try { final String jdbcString = "CREATE INDEX " + name + " ON " + table + "(" + attributes + ");"; final JdbcTemplate jdbc = new JdbcTemplate(dataSource); jdbc.execute(jdbcString); log.info(jdbcString); return true; } catch (final Throwable ex) { // Index does already exist (or an error has occurred). return false; } }
From source file:org.projectforge.database.DatabaseUpdateDao.java
/** * Executes the given String/* ww w . j av a 2s . c o m*/ * @since 3.3.48 * @param jdbcString * @param ignoreErrors If true (default) then errors will be caught and logged. * @return true if no error occurred (no exception was caught), otherwise false. */ public boolean execute(final String jdbcString, final boolean ignoreErrors) { accessCheck(true); final JdbcTemplate jdbc = new JdbcTemplate(dataSource); log.info(jdbcString); if (ignoreErrors == true) { try { jdbc.execute(jdbcString); } catch (final Throwable ex) { log.info(ex.getMessage(), ex); return false; } } else { jdbc.execute(jdbcString); } return true; }
From source file:org.projectforge.test.TestConfiguration.java
/** * Init and reinitialise context for each run *///from w w w. ja v a 2s.c om protected void initCtx() throws BeansException { if (ctx == null) { log.info("Initializing context: " + org.projectforge.common.StringHelper.listToString(", ", contextFiles)); try { // Build spring context ctx = new ClassPathXmlApplicationContext(contextFiles); ctx.getBeanFactory().autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false); final PropertyDataSource ds = ctx.getBean("dataSource", PropertyDataSource.class); this.databaseUrl = ds.getUrl(); final JdbcTemplate jdbc = new JdbcTemplate(ds); try { jdbc.execute("CHECKPOINT DEFRAG"); } catch (final org.springframework.jdbc.BadSqlGrammarException ex) { // ignore } final LocalSessionFactoryBean localSessionFactoryBean = (LocalSessionFactoryBean) ctx .getBean("&sessionFactory"); HibernateUtils.setConfiguration(localSessionFactoryBean.getConfiguration()); } catch (final Throwable ex) { log.error(ex.getMessage(), ex); throw new RuntimeException(ex); } } else { // Get a new HibernateTemplate each time ctx.getBeanFactory().autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false); } final Configuration cfg = ctx.getBean("configuration", Configuration.class); cfg.setBeanFactory(ctx.getBeanFactory()); // Bean factory need to be set. }
From source file:org.springframework.batch.test.DataSourceInitializer.java
private void doExecuteScript(final Resource scriptResource) { if (scriptResource == null || !scriptResource.exists()) return;/* w w w. j av a 2 s. c o m*/ TransactionTemplate transactionTemplate = new TransactionTemplate( new DataSourceTransactionManager(dataSource)); transactionTemplate.execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus status) { JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); String[] scripts; try { scripts = StringUtils.delimitedListToStringArray( stripComments(IOUtils.readLines(scriptResource.getInputStream())), ";"); } catch (IOException e) { throw new BeanInitializationException("Cannot load script from [" + scriptResource + "]", e); } for (int i = 0; i < scripts.length; i++) { String script = scripts[i].trim(); if (StringUtils.hasText(script)) { try { jdbcTemplate.execute(script); } catch (DataAccessException e) { if (ignoreFailedDrop && script.toLowerCase().startsWith("drop")) { logger.debug("DROP script failed (ignoring): " + script); } else { throw e; } } } } return null; } }); }
From source file:org.springframework.boot.actuate.autoconfigure.DataSourceMetricsAutoConfigurationTests.java
@Test public void multipleDataSources() { load(MultipleDataSourcesConfig.class); PublicMetrics bean = this.context.getBean(PublicMetrics.class); Collection<Metric<?>> metrics = bean.metrics(); assertMetrics(metrics, "datasource.tomcat.active", "datasource.tomcat.usage", "datasource.commonsDbcp.active", "datasource.commonsDbcp.usage"); // Hikari won't work unless a first connection has been retrieved JdbcTemplate jdbcTemplate = new JdbcTemplate(this.context.getBean("hikariDS", DataSource.class)); jdbcTemplate.execute(new ConnectionCallback<Void>() { @Override//from ww w.j av a 2s.c o m public Void doInConnection(Connection connection) throws SQLException, DataAccessException { return null; } }); Collection<Metric<?>> anotherMetrics = bean.metrics(); assertMetrics(anotherMetrics, "datasource.tomcat.active", "datasource.tomcat.usage", "datasource.hikariDS.active", "datasource.hikariDS.usage", "datasource.commonsDbcp.active", "datasource.commonsDbcp.usage"); }
From source file:org.springframework.boot.actuate.autoconfigure.metrics.PublicMetricsAutoConfigurationTests.java
@Test public void multipleDataSources() { load(MultipleDataSourcesConfig.class); PublicMetrics bean = this.context.getBean(DataSourcePublicMetrics.class); Collection<Metric<?>> metrics = bean.metrics(); assertMetrics(metrics, "datasource.tomcat.active", "datasource.tomcat.usage", "datasource.commonsDbcp.active", "datasource.commonsDbcp.usage"); // Hikari won't work unless a first connection has been retrieved JdbcTemplate jdbcTemplate = new JdbcTemplate(this.context.getBean("hikariDS", DataSource.class)); jdbcTemplate.execute((ConnectionCallback<Void>) (connection) -> null); Collection<Metric<?>> anotherMetrics = bean.metrics(); assertMetrics(anotherMetrics, "datasource.tomcat.active", "datasource.tomcat.usage", "datasource.hikariDS.active", "datasource.hikariDS.usage", "datasource.commonsDbcp.active", "datasource.commonsDbcp.usage"); }
From source file:org.springframework.boot.actuate.autoconfigure.PublicMetricsAutoConfigurationTests.java
@Test public void multipleDataSources() { load(MultipleDataSourcesConfig.class); PublicMetrics bean = this.context.getBean(DataSourcePublicMetrics.class); Collection<Metric<?>> metrics = bean.metrics(); assertMetrics(metrics, "datasource.tomcat.active", "datasource.tomcat.usage", "datasource.commonsDbcp.active", "datasource.commonsDbcp.usage"); // Hikari won't work unless a first connection has been retrieved JdbcTemplate jdbcTemplate = new JdbcTemplate(this.context.getBean("hikariDS", DataSource.class)); jdbcTemplate.execute(new ConnectionCallback<Void>() { @Override// w w w.ja v a 2 s. c o m public Void doInConnection(Connection connection) throws SQLException, DataAccessException { return null; } }); Collection<Metric<?>> anotherMetrics = bean.metrics(); assertMetrics(anotherMetrics, "datasource.tomcat.active", "datasource.tomcat.usage", "datasource.hikariDS.active", "datasource.hikariDS.usage", "datasource.commonsDbcp.active", "datasource.commonsDbcp.usage"); }
From source file:org.springframework.jdbc.core.JdbcTemplateTests.java
public void testConnectionCallback() throws Exception { replay();/*from ww w.ja v a 2 s .c o m*/ JdbcTemplate template = new JdbcTemplate(mockDataSource); template.setNativeJdbcExtractor(new PlainNativeJdbcExtractor()); Object result = template.execute(new ConnectionCallback() { public Object doInConnection(Connection con) { assertSame(mockConnection, con); return "test"; } }); assertEquals("test", result); }
From source file:org.springframework.jdbc.core.JdbcTemplateTests.java
public void testConnectionCallbackWithStatementSettings() throws Exception { MockControl ctrlStatement = MockControl.createControl(PreparedStatement.class); PreparedStatement mockStatement = (PreparedStatement) ctrlStatement.getMock(); mockConnection.prepareStatement("some SQL"); ctrlConnection.setReturnValue(mockStatement, 1); mockStatement.setFetchSize(10);/* w w w. j av a2s. c o m*/ ctrlStatement.setVoidCallable(1); mockStatement.setMaxRows(20); ctrlStatement.setVoidCallable(1); mockStatement.close(); ctrlStatement.setVoidCallable(1); replay(); JdbcTemplate template = new JdbcTemplate(mockDataSource); Object result = template.execute(new ConnectionCallback() { public Object doInConnection(Connection con) throws SQLException { PreparedStatement ps = con.prepareStatement("some SQL"); ps.close(); assertSame(mockConnection, new PlainNativeJdbcExtractor().getNativeConnection(con)); return "test"; } }); assertEquals("test", result); }
From source file:org.springframework.richclient.samples.petclinic.domain.InMemoryClinic.java
public void init() { super.init(dataSource); JdbcTemplate template = new JdbcTemplate(dataSource); // Schema: Petclinic template.execute( "CREATE TABLE vets (id INT NOT NULL IDENTITY PRIMARY KEY, first_name VARCHAR(30), last_name VARCHAR(30))"); template.execute("CREATE TABLE specialties (id INT NOT NULL IDENTITY PRIMARY KEY, name VARCHAR(80))"); template.execute("CREATE TABLE vet_specialties (vet_id INT NOT NULL, specialty_id INT NOT NULL)"); template.execute(//w w w . ja va2 s. com "alter table vet_specialties add constraint fk_vet_specialties_vets foreign key (vet_id) references vets(id)"); template.execute( "alter table vet_specialties add constraint fk_vet_specialties_specialties foreign key (specialty_id) references specialties(id)"); template.execute("CREATE TABLE types (id INT NOT NULL IDENTITY PRIMARY KEY, name VARCHAR(80))"); template.execute( "CREATE TABLE owners (id INT NOT NULL IDENTITY PRIMARY KEY, first_name VARCHAR(30), last_name VARCHAR(30), address VARCHAR(255), city VARCHAR(80), telephone VARCHAR(20))"); template.execute( "CREATE TABLE pets (id INT NOT NULL IDENTITY PRIMARY KEY, name VARCHAR(30), birth_date DATE, type_id INT NOT NULL, owner_id INT NOT NULL)"); template.execute( "alter table pets add constraint fk_pets_owners foreign key (owner_id) references owners(id)"); template.execute( "alter table pets add constraint fk_pets_types foreign key (type_id) references types(id)"); template.execute( "CREATE TABLE visits (id INT NOT NULL IDENTITY PRIMARY KEY, pet_id INT NOT NULL, visit_date DATE, description VARCHAR(255))"); template.execute( "alter table visits add constraint fk_visits_pets foreign key (pet_id) references pets(id)"); // Schema: Spring Security template.execute( "CREATE TABLE users (username VARCHAR(50) NOT NULL PRIMARY KEY, password VARCHAR(50) NOT NULL, enabled BIT NOT NULL)"); template.execute( "CREATE TABLE authorities (username VARCHAR(50) NOT NULL, authority VARCHAR(50) NOT NULL)"); template.execute( "alter table authorities add constraint fk_authorities_users foreign key (username) references users(username)"); // Data: Petclinic template.execute("INSERT INTO vets VALUES (1, 'James', 'Carter')"); template.execute("INSERT INTO vets VALUES (2, 'Helen', 'Leary')"); template.execute("INSERT INTO vets VALUES (3, 'Linda', 'Douglas')"); template.execute("INSERT INTO vets VALUES (4, 'Rafael', 'Ortega')"); template.execute("INSERT INTO vets VALUES (5, 'Henry', 'Stevens')"); template.execute("INSERT INTO vets VALUES (6, 'Sharon', 'Jenkins')"); template.execute("INSERT INTO specialties VALUES (1, 'radiology')"); template.execute("INSERT INTO specialties VALUES (2, 'surgery')"); template.execute("INSERT INTO specialties VALUES (3, 'dentistry')"); template.execute("INSERT INTO vet_specialties VALUES (2, 1);"); template.execute("INSERT INTO vet_specialties VALUES (3, 2);"); template.execute("INSERT INTO vet_specialties VALUES (3, 3);"); template.execute("INSERT INTO vet_specialties VALUES (4, 2);"); template.execute("INSERT INTO vet_specialties VALUES (5, 1);"); template.execute("INSERT INTO types VALUES (1, 'cat');"); template.execute("INSERT INTO types VALUES (2, 'dog');"); template.execute("INSERT INTO types VALUES (3, 'lizard');"); template.execute("INSERT INTO types VALUES (4, 'snake');"); template.execute("INSERT INTO types VALUES (5, 'bird');"); template.execute("INSERT INTO types VALUES (6, 'hamster');"); template.execute( "INSERT INTO owners VALUES (1, 'Keith', 'Donald', '110 W. Liberty St.', 'Madison', '6085551023');"); template.execute( "INSERT INTO owners VALUES (2, 'Keri', 'Donald', '638 Cardinal Ave.', 'Sun Prairie', '6085551749');"); template.execute( "INSERT INTO owners VALUES (3, 'Ronald', 'McDonald', '2693 Commerce St.', 'McFarland', '6085558763');"); template.execute( "INSERT INTO owners VALUES (4, 'Harold', 'Davis', '563 Friendly St.', 'Windsor', '6085553198');"); template.execute( "INSERT INTO owners VALUES (5, 'Peter', 'McTavish', '2387 S. Fair Way', 'Madison', '6085552765');"); template.execute( "INSERT INTO owners VALUES (6, 'Jean', 'Coleman', '105 N. Lake St.', 'Monona', '6085552654');"); template.execute( "INSERT INTO owners VALUES (7, 'Peter', 'Black', '1450 Oak Blvd.', 'Monona', '6085555387');"); template.execute( "INSERT INTO owners VALUES (8, 'Scott', 'Escobito', '345 Maple St.', 'Madison', '6085557683');"); template.execute( "INSERT INTO owners VALUES (9, 'David', 'Schroeder', '2749 Blackhawk Trail', 'Madison', '6085559435');"); template.execute( "INSERT INTO owners VALUES (10, 'Carlos', 'Estaban', '2335 Independence La.', 'Waunakee', '6085555487');"); template.execute("INSERT INTO pets VALUES (1, 'Leo', '2000-09-07', 1, 1)"); template.execute("INSERT INTO pets VALUES (2, 'Basil', '2002-08-06', 6, 2)"); template.execute("INSERT INTO pets VALUES (3, 'Rosy', '2001-04-17', 2, 3)"); template.execute("INSERT INTO pets VALUES (4, 'Jewel', '2000-03-07', 2, 3)"); template.execute("INSERT INTO pets VALUES (5, 'Iggy', '2000-11-30', 3, 4)"); template.execute("INSERT INTO pets VALUES (6, 'George', '2000-01-20', 4, 5)"); template.execute("INSERT INTO pets VALUES (7, 'Samantha', '1995-09-04', 1, 6)"); template.execute("INSERT INTO pets VALUES (8, 'Max', '1995-09-04', 1, 6)"); template.execute("INSERT INTO pets VALUES (9, 'Lucky', '1999-08-06', 5, 7)"); template.execute("INSERT INTO pets VALUES (10, 'Mulligan', '1997-02-24', 2, 8)"); template.execute("INSERT INTO pets VALUES (11, 'Freddy', '2000-03-09', 5, 9)"); template.execute("INSERT INTO pets VALUES (12, 'Lucky', '2000-06-24', 2, 10)"); template.execute("INSERT INTO pets VALUES (13, 'Sly', '2002-06-08', 1, 10)"); template.execute("INSERT INTO visits VALUES (1, 7, '1996-03-04', 'rabies shot')"); template.execute("INSERT INTO visits VALUES (2, 8, '1996-03-04', 'rabies shot')"); template.execute("INSERT INTO visits VALUES (3, 8, '1996-06-04', 'neutered')"); template.execute("INSERT INTO visits VALUES (4, 7, '1996-09-04', 'spayed')"); // Data: Spring Security template.execute("INSERT INTO users VALUES ('dianne', 'emu', true)"); template.execute("INSERT INTO users VALUES ('marissa', 'koala', true)"); template.execute("INSERT INTO users VALUES ('peter', 'opal', false)"); template.execute("INSERT INTO users VALUES ('scott', 'wombat', true)"); template.execute("INSERT INTO authorities VALUES ('marissa', 'ROLE_CLINIC_STAFF')"); template.execute("INSERT INTO authorities VALUES ('dianne', 'ROLE_CLINIC_STAFF')"); template.execute("INSERT INTO authorities VALUES ('peter', 'ROLE_CLINIC_CUSTOMER')"); template.execute("INSERT INTO authorities VALUES ('scott', 'ROLE_CLINIC_CUSTOMER')"); }