Java Code Examples for org.springframework.jdbc.core.JdbcTemplate

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project ANNIS, under directory /annis-service/src/main/java/annis/dao/.

Source file: SpringAnnisDao.java

  23 
vote

@Transactional @Override public <T>T executeQueryFunction(QueryData queryData,final SqlGenerator<QueryData,T> generator,final ResultSetExtractor<T> extractor){
  JdbcTemplate jdbcTemplate=getJdbcTemplate();
  queryData.setCorpusConfiguration(corpusConfiguration);
  queryData.setDocuments(metaDataFilter.getDocumentsForMetadata(queryData));
  for (  SqlSessionModifier sqlSessionModifier : sqlSessionModifiers) {
    sqlSessionModifier.modifySqlSession(jdbcTemplate,queryData);
  }
  return jdbcTemplate.query(generator.toSql(queryData),extractor);
}
 

Example 2

From project CamelInAction-source, under directory /chapter14/pojo-messaging/src/main/java/camelinaction/.

Source file: InventoryCreateTable.java

  22 
vote

public InventoryCreateTable(DataSource ds){
  JdbcTemplate jdbc=new JdbcTemplate(ds);
  try {
    jdbc.execute("drop table partner_inventory");
  }
 catch (  Exception e) {
  }
  jdbc.execute("create table partner_inventory " + "( supplier_id varchar(10), part_id varchar(10), name varchar(10), amount varchar(10) )");
}
 

Example 3

From project cas, under directory /cas-server-core/src/test/java/org/jasig/cas/ticket/registry/support/.

Source file: JdbcLockingStrategyTests.java

  22 
vote

/** 
 * @throws Exception on test setup.
 */
public void setUp() throws Exception {
  super.setUp();
  this.testDataSource=new SimpleDriverDataSource(new org.hsqldb.jdbcDriver(),"jdbc:hsqldb:mem:locktest","sa","");
  final JdbcTemplate tmpl=new JdbcTemplate(this.testDataSource);
  tmpl.execute(CREATE_TABLE_SQL);
  tmpl.execute(CREATE_PRI_KEY_SQL);
}
 

Example 4

From project jsecurity, under directory /samples/spring-hibernate/src/main/java/org/jsecurity/samples/sprhib/dao/.

Source file: BootstrapDataPopulator.java

  22 
vote

public void afterPropertiesSet() throws Exception {
  JdbcTemplate jdbcTemplate=new JdbcTemplate(this.dataSource);
  jdbcTemplate.execute("insert into roles values (1, 'user', 'The default role given to all users.')");
  jdbcTemplate.execute("insert into roles values (2, 'admin', 'The administrator role only given to site admins')");
  jdbcTemplate.execute("insert into roles_permissions values (2, 'user:*')");
  jdbcTemplate.execute("insert into users(id,username,email,password) values (1, 'admin', '[email protected]', '" + new Sha256Hash("admin").toHex() + "')");
  jdbcTemplate.execute("insert into users_roles values (1, 2)");
}
 

Example 5

From project riot, under directory /revolt/src/org/riotfamily/revolt/.

Source file: Script.java

  22 
vote

public void execute(DataSource dataSource){
  Assert.state(manualExecutionOnly == false,"This script must be manually executed.");
  JdbcTemplate template=new JdbcTemplate(dataSource);
  for (  String statement : getStatements()) {
    log.info(statement);
    template.execute(statement);
  }
}
 

Example 6

From project sched-assist, under directory /sched-assist-spi/src/test/java/org/jasig/schedassist/impl/owner/.

Source file: OwnerDefinedRelationshipDaoImplTest.java

  22 
vote

/** 
 * Creates the database. Also pulls the  {@link OwnerDao} from the configuration and registers a few sample  {@link IScheduleOwner}s.
 * @throws Exception
 */
@Before public void createDatabase() throws Exception {
  Resource createDdl=(Resource)this.applicationContext.getBean("createDdl");
  String sql=IOUtils.toString(createDdl.getInputStream());
  JdbcTemplate template=new JdbcTemplate((DataSource)this.applicationContext.getBean("dataSource"));
  template.execute(sql);
  for (int i=0; i < sampleOwners.length; i++) {
    ICalendarAccount calendarAccount=this.calendarAccountDao.getCalendarAccount("user" + i);
    sampleOwners[i]=ownerDao.register(calendarAccount);
  }
}
 

Example 7

From project shiro, under directory /samples/spring-hibernate/src/main/java/org/apache/shiro/samples/sprhib/dao/.

Source file: BootstrapDataPopulator.java

  22 
vote

public void afterPropertiesSet() throws Exception {
  JdbcTemplate jdbcTemplate=new JdbcTemplate(this.dataSource);
  jdbcTemplate.execute("insert into roles values (1, 'user', 'The default role given to all users.')");
  jdbcTemplate.execute("insert into roles values (2, 'admin', 'The administrator role only given to site admins')");
  jdbcTemplate.execute("insert into roles_permissions values (2, 'user:*')");
  jdbcTemplate.execute("insert into users(id,username,email,password) values (1, 'admin', '[email protected]', '" + new Sha256Hash("admin").toHex() + "')");
  jdbcTemplate.execute("insert into users_roles values (1, 2)");
}
 

Example 8

From project spring-activiti-sandbox, under directory /src/test/java/org/activiti/spring/test/transaction/.

Source file: UserBean.java

  22 
vote

@Transactional public void completeTask(String taskId){
  JdbcTemplate jdbcTemplate=new JdbcTemplate(dataSource);
  int nrOfRows=jdbcTemplate.update("insert into MY_TABLE values ('test');");
  if (nrOfRows != 1) {
    throw new RuntimeException("Insert into MY_TABLE failed");
  }
  taskService.complete(taskId);
}
 

Example 9

From project spring-security, under directory /acl/src/test/java/org/springframework/security/acls/jdbc/.

Source file: DatabaseSeeder.java

  22 
vote

public DatabaseSeeder(DataSource dataSource,Resource resource) throws IOException {
  Assert.notNull(dataSource,"dataSource required");
  Assert.notNull(resource,"resource required");
  JdbcTemplate template=new JdbcTemplate(dataSource);
  String sql=new String(FileCopyUtils.copyToByteArray(resource.getInputStream()));
  template.execute(sql);
}
 

Example 10

From project subsonic_1, under directory /subsonic-main/src/main/java/net/sourceforge/subsonic/dao/.

Source file: scratch.java

  22 
vote

public List<Redirection> getRedirections(int i){
  JdbcTemplate template=getJdbcTemplate(i);
  List result=template.query("select id, redirect_to, local_redirect_to, last_updated, last_read from redirection",new MyRowMapper());
  template.update("shutdown");
  return result;
}
 

Example 11

From project tesb-rt-se, under directory /sam/sam-server/src/test/java/org/talend/esb/sam/server/ui/test/.

Source file: UIProviderTest.java

  22 
vote

@SuppressWarnings("unchecked") private JsonObject fetchResult(Capture<RowMapper<JsonObject>> mapper,Capture<PreparedStatementCreator> creator,Map<String,String[]> parameters){
  List<Number> countRes=new ArrayList<Number>();
  countRes.add(10);
  UIProviderImpl provider=new UIProviderImpl();
  JdbcTemplate template=EasyMock.createMock(JdbcTemplate.class);
  provider.setJdbcTemplate(template);
  provider.setDialect(new DerbyDialect());
  EasyMock.expect(template.query(EasyMock.anyObject(PreparedStatementCreator.class),EasyMock.anyObject(RowMapper.class))).andReturn(countRes);
  EasyMock.expect(template.query(EasyMock.capture(creator),EasyMock.capture(mapper))).andReturn(objects);
  EasyMock.replay(template);
  JsonObject result=provider.getEvents(0,"base",new CriteriaAdapter(0,100,parameters));
  EasyMock.verify(template);
  return result;
}
 

Example 12

From project uaa, under directory /common/src/test/java/org/cloudfoundry/identity/uaa/scim/.

Source file: ScimUserEndpointsTests.java

  22 
vote

@After public void cleanUp(){
  JdbcTemplate jdbcTemplate=new JdbcTemplate(database);
  for (  ScimUser user : createdUsers) {
    jdbcTemplate.update("delete from users where id=?",user.getId());
  }
  for (  ScimGroup g : createdGroups) {
    jdbcTemplate.update("delete from groups where id=?",g.getId());
    jdbcTemplate.update("delete from group_membership where group_id=?",g.getId());
  }
}
 

Example 13

From project zen-project, under directory /zen-jsweb/src/main/java/com/nominanuda/jsweb/host/.

Source file: JdbcDataSource.java

  22 
vote

public static DataArray jsFunction_query(Context cx,Scriptable thisObj,Object[] args,Function funObj) throws Exception {
  JdbcTemplate jdbcTemplate=new JdbcTemplate(((JdbcDataSource)thisObj).getDataSource());
  List<?> result=jdbcTemplate.query(extractStatement(args),extractStatementArgs(args),rowMapper);
  DataArray ta=dataStruct.fromMapsAndCollections(result);
  return ta;
}
 

Example 14

From project greenhouse, under directory /src/test/java/com/springsource/greenhouse/account/.

Source file: JdbcAccountRepositoryTest.java

  21 
vote

public JdbcAccountRepositoryTest(){
  EmbeddedDatabase db=new GreenhouseTestDatabaseBuilder().member().testData(getClass()).getDatabase();
  transactional=new Transactional(db);
  jdbcTemplate=new JdbcTemplate(db);
  AccountMapper accountMapper=new AccountMapper(new StubFileStorage(),"http://localhost:8080/members/{profileKey}");
  accountRepository=new JdbcAccountRepository(jdbcTemplate,NoOpPasswordEncoder.getInstance(),accountMapper);
}
 

Example 15

From project gxa, under directory /annotator/src/main/java/uk/ac/ebi/gxa/annotator/loader/biomart/.

Source file: BioMartDbDAO.java

  21 
vote

public Collection<Pair<String,String>> getSynonyms(String dbNameTemplate,String version) throws BioMartException {
  try {
    final String dbName=findSynonymsDBName(dbNameTemplate,version);
    final JdbcTemplate template=createTemplate(dbName);
    return template.query("SELECT DISTINCT gene.stable_id, external_synonym.synonym \n" + "FROM gene, xref, external_synonym \n" + "WHERE gene.display_xref_id = xref.xref_id \n"+ "AND external_synonym.xref_id = xref.xref_id \n"+ "ORDER BY gene.stable_id; ",new RowMapper<Pair<String,String>>(){
      @Override public Pair<String,String> mapRow(      ResultSet rs,      int rowNum) throws SQLException {
        return Pair.create(rs.getString(1),rs.getString(2));
      }
    }
);
  }
 catch (  DataAccessException e) {
    log.error("Cannot fetch synonyms! URL: " + url + "/ name: "+ dbNameTemplate,e);
    throw new BioMartException("Cannot find database name to fetch synonyms. Please check Annotation Source configuration",e);
  }
}
 

Example 16

From project java-maven-tests, under directory /src/blogboard/blogboard-services/src/test/java/com/truward/blogboard/dao/.

Source file: BlogboardDaoTest.java

  21 
vote

@Test public void testSqlMapping() throws Exception {
  final JdbcTemplate template=new JdbcTemplate(dataSource);
  final Logger log=Logger.getLogger(BlogboardDaoTest.class);
  final List<SipAccount> accounts=template.query("select * from SIP_ACCOUNT order by ID;\n",new RowMapper<SipAccount>(){
    @Override public SipAccount mapRow(    ResultSet rs,    int rowNum) throws SQLException {
      final SipAccount account=new SipAccount();
      account.setId(rs.getInt("ID"));
      account.setNumber(rs.getString("SIP_NUMBER"));
      account.setPassword(rs.getString("SIP_PASSWORD"));
      return account;
    }
  }
);
  for (  final SipAccount a : accounts) {
    log.info(MessageFormat.format("RS : ID={0}, SIP_ACCOUNT={1}, SIP_PASSWORD={2}",a.getId(),a.getNumber(),a.getPassword()));
  }
{
    final SipAccount a=blogboardDao.getSipAccount(1);
    log.info(MessageFormat.format("JPA: ID={0}, SIP_ACCOUNT={1}, SIP_PASSWORD={2}",a.getId(),a.getNumber(),a.getPassword()));
  }
}
 

Example 17

From project jBilling, under directory /test/unit/com/sapienter/jbilling/server/mediation/task/.

Source file: JDBCReaderTest.java

  21 
vote

@Override protected void setUp() throws Exception {
  super.setUp();
  DriverManagerDataSource dataSource=new DriverManagerDataSource();
  dataSource.setDriverClassName(DRIVER);
  dataSource.setUrl(URL);
  dataSource.setUsername(USERNAME);
  dataSource.setPassword(PASSWORD);
  jdbcTemplate=new JdbcTemplate(dataSource);
  createTestSchema();
  reader.setParameters(parameters);
  reader.validate(new ArrayList<String>());
}
 

Example 18

From project khs-spring-batch-report-writer, under directory /src/test/java/com/khs/test/jdbc/datasource/.

Source file: DSInitializer.java

  21 
vote

private void doExecuteScript(final Resource scriptResource){
  if (scriptResource == null || !scriptResource.exists())   return;
  TransactionTemplate transactionTemplate=new TransactionTemplate(new DataSourceTransactionManager(dataSource));
  transactionTemplate.execute(new TransactionCallback(){
    @SuppressWarnings("unchecked") public Object 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;
    }
  }
);
}
 

Example 19

From project lorsource, under directory /src/main/java/ru/org/linux/comment/.

Source file: CommentDaoImpl.java

  21 
vote

@Autowired public void setDataSource(DataSource dataSource){
  jdbcTemplate=new JdbcTemplate(dataSource);
  insertMsgbase=new SimpleJdbcInsert(dataSource);
  insertMsgbase.setTableName("msgbase");
  insertMsgbase.usingColumns("id","message","bbcode");
}
 

Example 20

From project ohmageServer, under directory /src/org/ohmage/cache/.

Source file: KeyValueCache.java

  21 
vote

/** 
 * Reads the database for the information in the lookup table and populates its map with the gathered information. If there is an issue reading the database, it will just remain with the current lookup table it has.
 * @complexity O(n) where n is the number of keys in the database.
 */
protected synchronized void refreshMap(){
  if ((getLastUpdateTimestamp() + getUpdateFrequency()) > System.currentTimeMillis()) {
    return;
  }
  JdbcTemplate jdbcTemplate=new JdbcTemplate(getDataSource());
  List<KeyAndValue> keyAndValue;
  try {
    keyAndValue=jdbcTemplate.query(sqlForRetrievingValues,new RowMapper<KeyAndValue>(){
      @Override public KeyAndValue mapRow(      ResultSet rs,      int row) throws SQLException {
        return new KeyAndValue(rs.getString(keyColumn),rs.getString(valueColumn));
      }
    }
);
  }
 catch (  org.springframework.dao.DataAccessException e) {
    LOGGER.error("Error executing SQL '" + sqlForRetrievingValues + "'. Aborting cache refresh.");
    return;
  }
  Map<String,String> keyValueMap=new HashMap<String,String>();
  for (  KeyAndValue currStateAndId : keyAndValue) {
    keyValueMap.put(currStateAndId.key,currStateAndId.value);
  }
  this.keyValueMap=keyValueMap;
  setLastUpdateTimestamp(System.currentTimeMillis());
}
 

Example 21

From project Ohmage_Server_2, under directory /src/org/ohmage/cache/.

Source file: KeyValueCache.java

  21 
vote

/** 
 * Reads the database for the information in the lookup table and populates its map with the gathered information. If there is an issue reading the database, it will just remain with the current lookup table it has.
 * @complexity O(n) where n is the number of keys in the database.
 */
protected synchronized void refreshMap(){
  if ((getLastUpdateTimestamp() + getUpdateFrequency()) > System.currentTimeMillis()) {
    return;
  }
  JdbcTemplate jdbcTemplate=new JdbcTemplate(getDataSource());
  List<KeyAndValue> keyAndValue;
  try {
    keyAndValue=jdbcTemplate.query(sqlForRetrievingValues,new RowMapper<KeyAndValue>(){
      @Override public KeyAndValue mapRow(      ResultSet rs,      int row) throws SQLException {
        return new KeyAndValue(rs.getString(keyColumn),rs.getString(valueColumn));
      }
    }
);
  }
 catch (  org.springframework.dao.DataAccessException e) {
    LOGGER.error("Error executing SQL '" + sqlForRetrievingValues + "'. Aborting cache refresh.");
    return;
  }
  Map<String,String> keyValueMap=new HashMap<String,String>();
  for (  KeyAndValue currStateAndId : keyAndValue) {
    keyValueMap.put(currStateAndId.key,currStateAndId.value);
  }
  this.keyValueMap=keyValueMap;
  setLastUpdateTimestamp(System.currentTimeMillis());
}
 

Example 22

From project SeavusJB3, under directory /test/unit/com/sapienter/jbilling/server/mediation/task/.

Source file: JDBCReaderTest.java

  21 
vote

@Override protected void setUp() throws Exception {
  super.setUp();
  DriverManagerDataSource dataSource=new DriverManagerDataSource();
  dataSource.setDriverClassName(DRIVER);
  dataSource.setUrl(URL);
  dataSource.setUsername(USERNAME);
  dataSource.setPassword(PASSWORD);
  jdbcTemplate=new JdbcTemplate(dataSource);
  createTestSchema();
  reader.setParameters(parameters);
  reader.validate(new ArrayList<String>());
}
 

Example 23

From project spring-batch-examples, under directory /complex/src/test/java/de/langmi/spring/batch/examples/complex/jdbc/generic/export/.

Source file: JdbcGenericExportToDatabaseJobConfigurationTest.java

  21 
vote

/** 
 * Setup the test with some test data.
 * @throws Exception 
 */
@Before public void before() throws Exception {
  jdbcTemplate=new JdbcTemplate(dataSource);
  jdbcTemplate.execute(CREATE_ROOT_TABLE_SQL);
  jdbcTemplate.execute(CREATE_TARGET_TABLE_SQL);
  jdbcTemplate.batchUpdate(INSERT,new BatchPreparedStatementSetter(){
    @Override public void setValues(    PreparedStatement ps,    int i) throws SQLException {
      ps.setString(1,String.valueOf(i));
    }
    @Override public int getBatchSize(){
      return EXPECTED_COUNT;
    }
  }
);
}
 

Example 24

From project spring-flex, under directory /spring-flex-samples/spring-flex-testdrive/testdrive/src/main/java/org/springframework/flex/samples/util/.

Source file: DatabaseInitializer.java

  21 
vote

public DatabaseInitializer(DataSource ds){
  this.template=new JdbcTemplate(ds);
  createTableProduct();
  insertProducts();
  createTableContact();
  insertContacts();
  createTableIndustry();
  insertIndustries();
  createTableCompany();
  insertCompanies();
  createTableAccount();
  insertAccount();
}
 

Example 25

From project spring-hadoop, under directory /src/test/java/org/springframework/data/hadoop/hive/.

Source file: BasicHiveTest.java

  21 
vote

@Test public void testHiveConnection() throws Exception {
  JdbcTemplate jdbc=ctx.getBean("template",JdbcTemplate.class);
  String tableName="testHiveDriverTable";
  jdbc.execute("drop table if exists " + tableName);
  jdbc.execute("create table " + tableName + " (key int, value string)");
  jdbc.query("show tables",new ResultSetExtractor<String>(){
    public String extractData(    ResultSet rs) throws SQLException, DataAccessException {
      return "";
    }
  }
);
  jdbc.query("select count(1) from " + tableName,new ResultSetExtractor<String>(){
    public String extractData(    ResultSet rs) throws SQLException, DataAccessException {
      return "";
    }
  }
);
}
 

Example 26

From project spring-webflow, under directory /spring-webflow/src/test/java/org/springframework/webflow/persistence/.

Source file: AbstractPersistenceContextPropagationTests.java

  21 
vote

protected final void setUp() throws Exception {
  requestContext=new MockRequestContext();
  DataSource dataSource=createDataSource();
  jdbcTemplate=new JdbcTemplate(dataSource);
  populateDataBase(dataSource);
  setUpResources(dataSource);
}
 

Example 27

From project starflow, under directory /src/main/java/com/googlecode/starflow/core/key/impl/.

Source file: DefaultUniqueTableApp.java

  21 
vote

public DefaultUniqueTableApp(DataSource dataSource){
  jdbcTemplate=new JdbcTemplate(dataSource);
  this.selectSQL="SELECT code FROM WF_PRIMARYKEY WHERE name = ? FOR UPDATE";
  this.updateSQL="UPDATE WF_PRIMARYKEY SET code = code + ? WHERE name = ? ";
  this.insertSQL="INSERT INTO WF_PRIMARYKEY (code, name) VALUES (?, ?)";
}
 

Example 28

From project HMS, under directory /src/main/java/com/uff/hmstpa/model/persistence/.

Source file: AbstractModelDAO.java

  20 
vote

private void init(){
  Properties props=new Properties();
  try {
    props.load(new FileInputStream(databasePropertyFile));
    dataSource=new DriverManagerDataSource();
    dataSource.setDriverClassName(props.getProperty("driver"));
    dataSource.setUrl(props.getProperty("url"));
    dataSource.setUsername(props.getProperty("username"));
    dataSource.setPassword(props.getProperty("password"));
    jdbcTemplate=new JdbcTemplate(dataSource);
  }
 catch (  IOException ex) {
    ex.printStackTrace();
  }
}
 

Example 29

From project spring-social, under directory /spring-social-core/src/test/java/org/springframework/social/connect/jdbc/.

Source file: JdbcUsersConnectionRepositoryTest.java

  20 
vote

@Before public void setUp(){
  EmbeddedDatabaseFactory factory=new EmbeddedDatabaseFactory();
  if (testMySqlCompatiblity) {
    factory.setDatabaseConfigurer(new MySqlCompatibleH2DatabaseConfigurer());
  }
 else {
    factory.setDatabaseType(EmbeddedDatabaseType.H2);
  }
  ResourceDatabasePopulator populator=new ResourceDatabasePopulator();
  populator.addScript(new ClassPathResource(getSchemaSql(),getClass()));
  factory.setDatabasePopulator(populator);
  database=factory.getDatabase();
  dataAccessor=new JdbcTemplate(database);
  connectionFactoryRegistry=new ConnectionFactoryRegistry();
  connectionFactory=new TestFacebookConnectionFactory();
  connectionFactoryRegistry.addConnectionFactory(connectionFactory);
  usersConnectionRepository=new JdbcUsersConnectionRepository(database,connectionFactoryRegistry,Encryptors.noOpText());
  if (!getTablePrefix().equals("")) {
    usersConnectionRepository.setTablePrefix(getTablePrefix());
  }
  connectionRepository=usersConnectionRepository.createConnectionRepository("1");
}
 

Example 30

From project subsonic_2, under directory /subsonic-backend/src/main/java/net/sourceforge/subsonic/backend/dao/schema/.

Source file: Schema.java

  20 
vote

/** 
 * Returns whether the given table exists.
 * @param template The JDBC template to use.
 * @param table The table in question.
 * @return Whether the table exists.
 */
protected boolean tableExists(JdbcTemplate template,String table){
  try {
    template.execute("select 1 from " + table);
  }
 catch (  Exception x) {
    return false;
  }
  return true;
}
 

Example 31

From project Supersonic, under directory /subsonic-main/src/main/java/net/sourceforge/subsonic/dao/schema/.

Source file: Schema31.java

  20 
vote

public void execute(JdbcTemplate template){
  if (template.queryForInt("select count(*) from version where version = 7") == 0) {
    LOG.info("Updating database schema to version 7.");
    template.execute("insert into version values (7)");
  }
  if (!columnExists(template,"enabled","music_file_info")) {
    LOG.info("Database column 'music_file_info.enabled' not found.  Creating it.");
    template.execute("alter table music_file_info add enabled boolean default true not null");
    LOG.info("Database column 'music_file_info.enabled' was added successfully.");
  }
  if (!columnExists(template,"default_active","transcoding")) {
    LOG.info("Database column 'transcoding.default_active' not found.  Creating it.");
    template.execute("alter table transcoding add default_active boolean default true not null");
    LOG.info("Database column 'transcoding.default_active' was added successfully.");
  }
}
 

Example 32

From project arquillian-showcase, under directory /spring/spring-jdbc/src/test/java/com/acme/spring/jdbc/.

Source file: JdbcTestHelper.java

  19 
vote

/** 
 * <p>Executes a sql script.</p>
 * @param jdbcTemplate the jdbc template
 * @param fileName     the file name
 * @throws IOException if any error occurs
 */
public static void runScript(JdbcTemplate jdbcTemplate,String fileName) throws IOException {
  InputStream input=Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
  BufferedReader inputReader=new BufferedReader(new InputStreamReader(input));
  StringBuilder stringBuilder=new StringBuilder();
  String line;
  while ((line=inputReader.readLine()) != null) {
    if (!line.startsWith("--")) {
      stringBuilder.append(line);
    }
  }
  String[] commands=stringBuilder.toString().split(";");
  for (  String command : commands) {
    jdbcTemplate.execute(command);
  }
}
 

Example 33

From project fire-samples, under directory /cache-demo/src/main/java/demo/vmware/datasync/.

Source file: CacheWriterAutoMapped.java

  19 
vote

/** 
 * Future behavior: attempts to do an insert and then an update if the insert fails.
 * @param arg0
 */
void insertOrUpdate(EntryEvent<Object,Object> arg0){
  String regionName=arg0.getRegion().getName();
  SimpleJdbcInsert insert=new SimpleJdbcInsert(new JdbcTemplate(dataSource)).withTableName(dataLoaderUtilities.getMappedTableName(regionName));
  SqlParameterSource sqlArgsSource=new BeanPropertyItemSqlParameterSourceProvider().createSqlParameterSource(arg0.getNewValue());
  try {
    insert.execute(sqlArgsSource);
  }
 catch (  Exception e) {
    LOG.warn("failed because of ",e);
  }
}
 

Example 34

From project miso-lims, under directory /sqlstore/src/main/java/uk/ac/bbsrc/tgac/miso/sqlstore/util/.

Source file: DbUtils.java

  19 
vote

public static long getAutoIncrement(JdbcTemplate template,String tableName) throws IOException {
  final String q="SHOW TABLE STATUS LIKE '" + tableName + "'";
  Map<String,Object> rs=template.queryForMap(q);
  Object ai=rs.get("Auto_increment");
  if (ai != null) {
    return new Long(ai.toString());
  }
 else {
    throw new IOException("Cannot resolve Auto_increment value from DBMS metadata tables");
  }
}
 

Example 35

From project qcadoo, under directory /qcadoo-model/src/test/java/com/qcadoo/model/integration/.

Source file: IntegrationTest.java

  19 
vote

@BeforeClass public static void classInit() throws Exception {
  MultiTenantUtil multiTenantUtil=new MultiTenantUtil();
  ReflectionTestUtils.setField(multiTenantUtil,"multiTenantService",new DefaultMultiTenantService());
  multiTenantUtil.init();
  applicationContext=new ClassPathXmlApplicationContext();
  applicationContext.getEnvironment().setActiveProfiles("standalone");
  applicationContext.setConfigLocation("spring.xml");
  applicationContext.refresh();
  dataDefinitionService=applicationContext.getBean(InternalDataDefinitionService.class);
  sessionFactory=applicationContext.getBean("sessionFactory",SessionFactory.class);
  jdbcTemplate=applicationContext.getBean(JdbcTemplate.class);
  verifyHooks=applicationContext.getBean(VerifyHooks.class);
}
 

Example 36

From project spring-data-jdbc-ext, under directory /spring-data-jdbc-core/src/main/java/org/springframework/data/jdbc/query/.

Source file: QueryDslJdbcTemplate.java

  19 
vote

public QueryDslJdbcTemplate(JdbcTemplate jdbcTemplate){
  this.jdbcTemplate=jdbcTemplate;
  DatabaseType dbType;
  try {
    dbType=DatabaseType.fromMetaData(jdbcTemplate.getDataSource());
  }
 catch (  MetaDataAccessException e) {
    throw new DataAccessResourceFailureException("Unable to determine database type: ",e);
  }
  if (dbType == DatabaseType.DERBY) {
    this.dialect=new DerbyTemplates();
  }
 else   if (dbType == DatabaseType.H2) {
    this.dialect=new H2Templates();
  }
 else   if (dbType == DatabaseType.HSQL) {
    this.dialect=new HSQLDBTemplates();
  }
 else   if (dbType == DatabaseType.MYSQL) {
    this.dialect=new MySQLTemplates();
  }
 else   if (dbType == DatabaseType.ORACLE) {
    this.dialect=new OracleTemplates();
  }
 else   if (dbType == DatabaseType.POSTGRES) {
    this.dialect=new PostgresTemplates();
  }
 else   if (dbType == DatabaseType.SQLSERVER) {
    this.dialect=new SQLServerTemplates();
  }
 else {
    throw new InvalidDataAccessResourceUsageException(dbType + " is an unsupported database");
  }
}
 

Example 37

From project spring-security-samples-securemail, under directory /src/main/java/org/springframework/security/samples/mail/.

Source file: JdbcMailUserService.java

  19 
vote

@Autowired public JdbcMailUserService(JdbcTemplate jdbcTemplate){
  if (jdbcTemplate == null) {
    throw new IllegalArgumentException("jdbcTemplate cannot be null");
  }
  this.jdbcTemplate=jdbcTemplate;
}
 

Example 38

From project subsonic, under directory /subsonic-backend/src/main/java/net/sourceforge/subsonic/backend/dao/schema/.

Source file: Schema.java

  19 
vote

/** 
 * Returns whether the given table exists.
 * @param template The JDBC template to use.
 * @param table The table in question.
 * @return Whether the table exists.
 */
protected boolean tableExists(JdbcTemplate template,String table){
  try {
    template.execute("select 1 from " + table);
  }
 catch (  Exception x) {
    return false;
  }
  return true;
}
 

Example 39

From project tb-diamond_1, under directory /diamond-server/src/main/java/com/taobao/diamond/server/utils/.

Source file: PaginationHelper.java

  19 
vote

/** 
 * ???
 * @param jt jdbcTemplate
 * @param sqlCountRows ?????SQL
 * @param sqlFetchRows ?????sql
 * @param args ????
 * @param pageNo ??
 * @param pageSize ????
 * @param rowMapper
 * @return
 */
public Page<E> fetchPage(final JdbcTemplate jt,final String sqlCountRows,final String sqlFetchRows,final Object args[],final int pageNo,final int pageSize,final ParameterizedRowMapper<E> rowMapper){
  if (pageSize == 0) {
    return null;
  }
  final int rowCount=jt.queryForInt(sqlCountRows,args);
  int pageCount=rowCount / pageSize;
  if (rowCount > pageSize * pageCount) {
    pageCount++;
  }
  final Page<E> page=new Page<E>();
  page.setPageNumber(pageNo);
  page.setPagesAvailable(pageCount);
  page.setTotalCount(rowCount);
  if (pageNo > pageCount)   return null;
  final int startRow=(pageNo - 1) * pageSize;
  final String selectSQL=sqlFetchRows + " limit " + startRow+ ","+ pageSize;
  jt.query(selectSQL,args,new ResultSetExtractor(){
    public Object extractData(    ResultSet rs) throws SQLException, DataAccessException {
      final List<E> pageItems=page.getPageItems();
      int currentRow=0;
      while (rs.next()) {
        pageItems.add(rowMapper.mapRow(rs,currentRow++));
      }
      return page;
    }
  }
);
  return page;
}
 

Example 40

From project xeneo-db-impl, under directory /src/main/java/org/xeneo/db/.

Source file: JdbcCase.java

  19 
vote

public JdbcCase(JdbcTemplate jdbcTemplate,UserManager userManager,String caseURI){
  this.jdbcTemplate=jdbcTemplate;
  this.userManager=userManager;
  this.caseURI=caseURI;
  this.updateMe=true;
}