Embedded database support Data access with JDBC
19.8 Embedded database support
The org.springframework.jdbc.datasource.embedded package provides support for embedded Java database engines. Support for HSQL , H2 , and Derby is provided natively. You can also use an extensible API to plug in new embedded database types and DataSource implementations. Why use an embedded database? An embedded database is useful during the development phase of a project because of its lightweight nature. Benefits include ease of configuration, quick startup time, testability, and the ability to rapidly evolve SQL during development. Creating an embedded database using Spring XML If you want to expose an embedded database instance as a bean in a Spring ApplicationContext , use the embedded-database tag in the spring-jdbc namespace: jdbc:embedded-database id = dataSource generate-name = true jdbc:script location = classpath:schema.sql jdbc:script location = classpath:test-data.sql jdbc:embedded-database The preceding configuration creates an embedded HSQL database populated with SQL from schema.sql and test-data.sql resources in the root of the classpath. In addition, as a best practice, the embedded database will be assigned a uniquely generated name. The embedded database is made available to the Spring container as a bean of type javax.sql.DataSource which can then be injected into data access objects as needed. Creating an embedded database programmatically The EmbeddedDatabaseBuilder class provides a fluent API for constructing an embedded database programmatically. Use this when you need to create an embedded database in a standalone environment or in a standalone integration test like in the following example. EmbeddedDatabase db = new EmbeddedDatabaseBuilder .generateUniqueNametrue .setTypeH2 .setScriptEncoding UTF-8 .ignoreFailedDropstrue .addScript schema.sql .addScripts user_data.sql , country_data.sql .build; perform actions against the db EmbeddedDatabase extends javax.sql.DataSource db.shutdown Consult the Javadoc for EmbeddedDatabaseBuilder for further details on all supported options. The EmbeddedDatabaseBuilder can also be used to create an embedded database using Java Config like in the following example. 4.3.9.RELEASE Spring Framework 441 Configuration public class DataSourceConfig { Bean public DataSource dataSource { return new EmbeddedDatabaseBuilder .generateUniqueNametrue .setTypeH2 .setScriptEncoding UTF-8 .ignoreFailedDropstrue .addScript schema.sql .addScripts user_data.sql , country_data.sql .build; } } Selecting the embedded database type Using HSQL Spring supports HSQL 1.8.0 and above. HSQL is the default embedded database if no type is specified explicitly. To specify HSQL explicitly, set the type attribute of the embedded-database tag to HSQL . If you are using the builder API, call the setTypeEmbeddedDatabaseType method with EmbeddedDatabaseType.HSQL . Using H2 Spring supports the H2 database as well. To enable H2, set the type attribute of the embedded- database tag to H2 . If you are using the builder API, call the setTypeEmbeddedDatabaseType method with EmbeddedDatabaseType.H2 . Using Derby Spring also supports Apache Derby 10.5 and above. To enable Derby, set the type attribute of the embedded-database tag to DERBY . If you are using the builder API, call the setTypeEmbeddedDatabaseType method with EmbeddedDatabaseType.DERBY . Testing data access logic with an embedded database Embedded databases provide a lightweight way to test data access code. The following is a data access integration test template that uses an embedded database. Using a template like this can be useful for one-offs when the embedded database does not need to be reused across test classes. However, if you wish to create an embedded database that is shared within a test suite, consider using the Spring TestContext Framework and configuring the embedded database as a bean in the Spring ApplicationContext as described in the section called “Creating an embedded database using Spring XML” and the section called “Creating an embedded database programmatically”. 4.3.9.RELEASE Spring Framework 442 public class DataAccessIntegrationTestTemplate { private EmbeddedDatabase db; Before public void setUp { creates an HSQL in-memory database populated from default scripts classpath:schema.sql and classpath:data.sql db = new EmbeddedDatabaseBuilder .generateUniqueNametrue .addDefaultScripts .build; } Test public void testDataAccess { JdbcTemplate template = new JdbcTemplatedb; template.query ... ; } After public void tearDown { db.shutdown; } } Generating unique names for embedded databases Development teams often encounter errors with embedded databases if their test suite inadvertently attempts to recreate additional instances of the same database. This can happen quite easily if an XML configuration file or Configuration class is responsible for creating an embedded database and the corresponding configuration is then reused across multiple testing scenarios within the same test suite i.e., within the same JVM process –- for example, integration tests against embedded databases whose ApplicationContext configuration only differs with regard to which bean definition profiles are active. The root cause of such errors is the fact that Spring’s EmbeddedDatabaseFactory used internally by both the jdbc:embedded-database XML namespace element and the EmbeddedDatabaseBuilder for Java Config will set the name of the embedded database to testdb if not otherwise specified. For the case of jdbc:embedded-database , the embedded database is typically assigned a name equal to the bean’s id i.e., often something like dataSource . Thus, subsequent attempts to create an embedded database will not result in a new database. Instead, the same JDBC connection URL will be reused, and attempts to create a new embedded database will actually point to an existing embedded database created from the same configuration. To address this common issue Spring Framework 4.2 provides support for generating unique names for embedded databases. To enable the use of generated names, use one of the following options. • EmbeddedDatabaseFactory.setGenerateUniqueDatabaseName • EmbeddedDatabaseBuilder.generateUniqueName • jdbc:embedded-database generate-name=true … Extending the embedded database support Spring JDBC embedded database support can be extended in two ways: 4.3.9.RELEASE Spring Framework 443 • Implement EmbeddedDatabaseConfigurer to support a new embedded database type. • Implement DataSourceFactory to support a new DataSource implementation, such as a connection pool to manage embedded database connections. You are encouraged to contribute back extensions to the Spring community at jira.spring.io .19.9 Initializing a DataSource
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