Initializing a DataSource Data access with JDBC
19.9 Initializing a DataSource
The org.springframework.jdbc.datasource.init package provides support for initializing an existing DataSource . The embedded database support provides one option for creating and initializing a DataSource for an application, but sometimes you need to initialize an instance running on a server somewhere. Initializing a database using Spring XML If you want to initialize a database and you can provide a reference to a DataSource bean, use the initialize-database tag in the spring-jdbc namespace: jdbc:initialize-database data-source = dataSource jdbc:script location = classpath:comfoosqldb-schema.sql jdbc:script location = classpath:comfoosqldb-test-data.sql jdbc:initialize-database The example above executes the two scripts specified against the database: the first script creates a schema, and the second populates tables with a test data set. The script locations can also be patterns with wildcards in the usual ant style used for resources in Spring e.g. classpath:comfoo sql-data.sql . If a pattern is used, the scripts are executed in lexical order of their URL or filename. The default behavior of the database initializer is to unconditionally execute the scripts provided. This will not always be what you want, for instance, if you are executing the scripts against a database that already has test data in it. The likelihood of accidentally deleting data is reduced by following the common pattern as shown above of creating the tables first and then inserting the data — the first step will fail if the tables already exist. However, to gain more control over the creation and deletion of existing data, the XML namespace provides a few additional options. The first is a flag to switch the initialization on and off. This can be set according to the environment e.g. to pull a boolean value from system properties or an environment bean, for example: jdbc:initialize-database data-source = dataSource enabled={systemProperties.INITIALIZE_DATABASE} jdbc:script location = ... jdbc:initialize-database The second option to control what happens with existing data is to be more tolerant of failures. To this end you can control the ability of the initializer to ignore certain errors in the SQL it executes from the scripts, for example: jdbc:initialize-database data-source = dataSource ignore-failures=DROPS jdbc:script location = ... jdbc:initialize-database In this example we are saying we expect that sometimes the scripts will be executed against an empty database, and there are some DROP statements in the scripts which would therefore fail. So failed SQL 4.3.9.RELEASE Spring Framework 444 DROP statements will be ignored, but other failures will cause an exception. This is useful if your SQL dialect doesn’t support DROP … IF EXISTS or similar but you want to unconditionally remove all test data before re-creating it. In that case the first script is usually a set of DROP statements, followed by a set of CREATE statements. The ignore-failures option can be set to NONE the default, DROPS ignore failed drops, or ALL ignore all failures. Each statement should be separated by ; or a new line if the ; character is not present at all in the script. You can control that globally or script by script, for example: jdbc:initialize-database data-source = dataSource separator= jdbc:script location = classpath:comfoosqldb-schema.sql separator=; jdbc:script location = classpath:comfoosqldb-test-data-1.sql jdbc:script location = classpath:comfoosqldb-test-data-2.sql jdbc:initialize-database In this example, the two test-data scripts use as statement separator and only the db- schema.sql uses ; . This configuration specifies that the default separator is and override that default for the db-schema script. If you need more control than you get from the XML namespace, you can simply use the DataSourceInitializer directly and define it as a component in your application. Initialization of other components that depend on the database A large class of applications can just use the database initializer with no further complications: those that do not use the database until after the Spring context has started. If your application is not one of those then you might need to read the rest of this section. The database initializer depends on a DataSource instance and executes the scripts provided in its initialization callback analogous to an init-method in an XML bean definition, a PostConstruct method in a component, or the afterPropertiesSet method in a component that implements InitializingBean . If other beans depend on the same data source and also use the data source in an initialization callback, then there might be a problem because the data has not yet been initialized. A common example of this is a cache that initializes eagerly and loads data from the database on application startup. To get around this issue you have two options: change your cache initialization strategy to a later phase, or ensure that the database initializer is initialized first. The first option might be easy if the application is in your control, and not otherwise. Some suggestions for how to implement this include: • Make the cache initialize lazily on first usage, which improves application startup time. • Have your cache or a separate component that initializes the cache implement Lifecycle or SmartLifecycle . When the application context starts up a SmartLifecycle can be automatically started if its autoStartup flag is set, and a Lifecycle can be started manually by calling ConfigurableApplicationContext.start on the enclosing context. • Use a Spring ApplicationEvent or similar custom observer mechanism to trigger the cache initialization. ContextRefreshedEvent is always published by the context when it is ready for use after all beans have been initialized, so that is often a useful hook this is how the SmartLifecycle works by default. 4.3.9.RELEASE Spring Framework 445 The second option can also be easy. Some suggestions on how to implement this include: • Rely on the default behavior of the Spring BeanFactory , which is that beans are initialized in registration order. You can easily arrange that by adopting the common practice of a set of import elements in XML configuration that order your application modules, and ensure that the database and database initialization are listed first. • Separate the DataSource and the business components that use it, and control their startup order by putting them in separate ApplicationContext instances e.g. the parent context contains the DataSource , and child context contains the business components. This structure is common in Spring web applications but can be more generally applied. 4.3.9.RELEASE Spring Framework 44620. Object Relational Mapping ORM Data Access
Parts
» Dependency Injection and Inversion of Control Framework Modules
» Usage scenarios Introduction to the Spring Framework
» Java EE 6 and 7 Groovy Bean Definition DSL
» Core Container Improvements General Web Improvements
» WebSocket, SockJS, and STOMP Messaging Testing Improvements
» JMS Improvements Caching Improvements
» Web Improvements New Features and Enhancements in Spring Framework 1
» WebSocket Messaging Improvements Testing Improvements
» Core Container Improvements New Features and Enhancements in Spring Framework 4.2
» Data Access Improvements JMS Improvements Web Improvements
» Core Container Improvements Data Access Improvements Caching Improvements
» JMS Improvements Web Improvements WebSocket Messaging Improvements Testing Improvements
» Introduction to the Spring IoC container and beans
» Container overview The IoC container
» Bean overview The IoC container
» Dependencies The IoC container
» y.Baz beans The IoC container
» driverClassName = username = The IoC container
» email = spouse-ref = The IoC container
» y.Bar bean y.Foo constructor-arg y.Foo c:bar-ref baz-ref = y.Foo c:_0-ref _1-ref =
» y.z.MyValueCalculator b.c.ReplacementComputeValue Bean scopes
» y.Foo property Customizing the nature of a bean
» Bean definition inheritance The IoC container
» Container Extension Points The IoC container
» Annotation-based container configuration The IoC container
» Classpath scanning and managed components
» Using JSR 330 Standard Annotations
» Java-based container configuration The IoC container
» Environment abstraction The IoC container
» Registering a LoadTimeWeaver Additional Capabilities of the ApplicationContext
» The BeanFactory The IoC container
» Introduction The Resource interface
» Built-in Resource implementations Resources
» The ResourceLoaderAware interface Resources
» Resources as dependencies Application contexts and Resource paths
» Introduction Validation, Data Binding, and Type Conversion
» Validation using Spring’s Validator interface
» Resolving codes to error messages Bean manipulation and the BeanWrapper
» Spring Type Conversion Validation, Data Binding, and Type Conversion
» Spring Field Formatting Validation, Data Binding, and Type Conversion
» Configuring a global date time format
» Spring Validation Validation, Data Binding, and Type Conversion
» Introduction Feature Overview Spring Expression Language SpEL
» Expression Evaluation using Spring’s Expression Interface
» Expression support for defining bean definitions
» Language Reference Spring Expression Language SpEL
» 3e0 4 .getValueDouble. 4e0 2 .getValueDouble.
» Classes used in the examples
» Introduction Aspect Oriented Programming with Spring
» Schema-based AOP support Aspect Oriented Programming with Spring
» y.service.DefaultFooService y.SimpleProfiler aop:config
» Choosing which AOP declaration style to use
» Mixing aspect types Proxying mechanisms
» Introduction Pointcut API in Spring
» Advisor API in Spring Using the ProxyFactoryBean to create AOP proxies
» Concise proxy definitions Spring AOP APIs
» Creating AOP proxies programmatically with the ProxyFactory Manipulating advised objects
» Using the auto-proxy facility
» Using TargetSources Spring AOP APIs
» Mock Objects Unit Testing support Classes
» Overview Goals of Integration Testing
» JDBC Testing Support Annotations
» Spring TestContext Framework Integration Testing
» loginAction-ref = username = userPreferences-ref = theme =
» PetClinic Example Integration Testing
» Understanding the Spring Framework transaction abstraction
» Synchronizing resources with transactions
» Declarative transaction management Transaction Management
» y.service.DefaultFooService Transaction Management
» y.service.DefaultFooService y.SimpleProfiler y.service.DefaultFooService
» y.SimpleProfiler Transaction Management
» Programmatic transaction management Transaction Management
» Choosing between programmatic and declarative transaction management Transaction bound event
» Application server-specific integration Transaction Management
» Introduction Consistent exception hierarchy
» Annotations used for configuring DAO or Repository classes
» Introduction to Spring Framework JDBC
» Using the JDBC core classes to control basic JDBC processing and error handling
» Controlling database connections Data access with JDBC
» JDBC batch operations Data access with JDBC
» Simplifying JDBC operations with the SimpleJdbc classes
» Modeling JDBC operations as Java objects
» Common problems with parameter and data value handling
» Embedded database support Data access with JDBC
» Initializing a DataSource Data access with JDBC
» Introduction to ORM with Spring
» General ORM integration considerations
» Hibernate Object Relational Mapping ORM Data Access
» JDO Object Relational Mapping ORM Data Access
» Introduction Marshaller and Unmarshaller
» Using Marshaller and Unmarshaller
» XML Schema-based Configuration JAXB
» Castor Marshalling XML using OX Mappers
» XMLBeans JiBX Marshalling XML using OX Mappers
» XStream Marshalling XML using OX Mappers
» Introduction to Spring Web MVC framework
» The DispatcherServlet Web MVC framework
» Handler mappings Web MVC framework
» Resolving views Web MVC framework
» Using flash attributes Web MVC framework
» Building URIs Web MVC framework
» Using locales Web MVC framework
» Using themes Web MVC framework
» Spring’s multipart file upload support
» Handling exceptions Web MVC framework
» Web Security Convention over configuration support
» y.RegistrationController HTTP caching support
» Code-based Servlet container initialization
» Configuring Spring MVC Web MVC framework
» simpleDateFormat = Web MVC framework
» Introduction Thymeleaf Groovy Markup Templates
» Velocity FreeMarker View technologies
» Document views PDFExcel Property
» Feed Views JSON Mapping View
» Introduction Integrating with other web frameworks
» Common configuration Integrating with other web frameworks
» JavaServer Faces 1.2 Apache Struts 2.x
» Introduction Portlet MVC Framework
» The DispatcherPortlet Portlet MVC Framework
» The ViewRendererServlet Controllers Portlet MVC Framework
» Handler mappings Portlet MVC Framework
» Views and resolving them Multipart file upload support
» Handling exceptions Annotation-based controller configuration
» absolute-ordering absolute-ordering WebSocket API
» SockJS Fallback Options WebSocket Support
» STOMP Over WebSocket Messaging Architecture
» Introduction Controller method CORS configuration
» Global CORS configuration Advanced Customization
» Introduction Remoting and web services using Spring
» Using Hessian or Burlap to remotely call services via HTTP
» Exposing services using HTTP invokers
» Web services Remoting and web services using Spring
» JMS Remoting and web services using Spring
» Accessing RESTful services on the Client
» Introduction Accessing EJBs Enterprise JavaBeans EJB integration
» Introduction JMS Java Message Service
» Using Spring JMS JMS Java Message Service
» Sending a Message JMS Java Message Service
» Receiving a message JMS Java Message Service
» Support for JCA Message Endpoints
» Annotation-driven listener endpoints JMS Java Message Service
» JMS namespace support JMS Java Message Service
» Introduction Exporting your beans to JMX
» Controlling the management interface of your beans
» Controlling the ObjectNames for your beans
» Accessing MBeans via Proxies
» Introduction Configuring CCI JCA CCI
» Using Spring’s CCI access support
» Modeling CCI access as operation objects
» Using the JavaMail MimeMessageHelper
» Introduction The Spring TaskExecutor abstraction
» The Spring TaskScheduler abstraction
» Annotation Support for Scheduling and Asynchronous Execution
» The task namespace Task Execution and Scheduling
» Introduction A first example
» y.DefaultBookingService property Defining beans that are backed by dynamic languages
» y.DefaultBookingService property Dynamic language support
» Scenarios Dynamic language support
» Bits and bobs y.DefaultBookingService property
» Introduction Understanding the cache abstraction
» Declarative annotation-based caching Cache Abstraction
» JCache JSR-107 annotations Cache Abstraction
» Declarative XML-based caching y.service.DefaultBookService
» Configuring the cache storage name =
» Classic ORM usage Classic Spring Usage
» JMS Usage Classic Spring Usage
» Concise proxy definitions Classic Spring AOP Usage
» Using the autoproxy facility
» Using TargetSources Classic Spring AOP Usage
» Introduction XML Schema-based configuration
» Introduction Authoring the schema
» Coding a NamespaceHandler Extensible XML authoring
» BeanDefinitionParser Extensible XML authoring
» Registering the handler and the schema
» Using a custom extension in your Spring XML configuration Meatier examples
» Introduction The argument tag The bind tag
» The escapeBody tag The eval tag The hasBindErrors tag
» The htmlEscape tag The message tag
» The nestedPath tag The param tag The theme tag
» The transform tag The url tag
» Introduction The button tag The checkbox tag
» The checkboxes tag The errors tag
» The option tag The options tag
» The password tag The radiobutton tag
Show more