So, I see all answer this problem in Stackoverflow, but not be of any help to me.
(
SpringMVC+Thymeleaf ,error message is : template might not exist or might not be accessible by any of the configured Template Resolvers
Error resolving template "pages", template might not exist or might not be accessible by any of the configured Template Resolvers
SpringMVC+Thymeleaf ,error message is : template might not exist or might not be accessible by any of the configured Template Resolvers
...
)
Here my servlet-context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.2.xsd">
<!-- Basic Configurations -->
<context:annotation-config/>
<context:component-scan base-package="com.podium.italia.controller"/>
<context:component-scan base-package="com.podium.italia.service"/>
<context:component-scan base-package="com.podium.italia.model"/>
<context:component-scan base-package="com.podium.italia.repository"/>
<mvc:annotation-driven />
<mvc:default-servlet-handler />
<!-- i18n -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="WEB-INF/i18n"/>
<property name="defaultEncoding" value="UTF-8"/>
<property name="useCodeAsDefaultMessage" value="true"/>
</bean>
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.FixedLocaleResolver">
<property name="defaultLocale" value="en"/>
</bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
<!-- Email support -->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.gmail.com" />
<property name="port" value="587" />
<property name="protocol" value="smtp" />
<property name="username" value="smmailsender#gmail.com" />
<property name="password" value="Style#mix2014" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
<prop key="mail.smtp.quitwait">true</prop>
</props>
</property>
</bean>
<!-- THYMELEAF: Template Resolver for email templates -->
<bean id="emailTemplateResolver" class="org.thymeleaf.templateresolver.ClassLoaderTemplateResolver">
<property name="prefix" value="mail/" />
<property name="templateMode" value="HTML5" />
<property name="characterEncoding" value="UTF-8" />
<property name="order" value="1" />
</bean>
<!-- THYMELEAF: Template Resolver for webapp pages -->
<!-- (we would not need this if our app was not web) -->
<bean id="webTemplateResolver" class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
<property name="prefix" value="/WEB-INF/" />
<property name="templateMode" value="HTML5" />
<property name="characterEncoding" value="UTF-8" />
<property name="order" value="2" />
</bean>
<!-- THYMELEAF: Template Engine (Spring3-specific version) -->
<bean id="templateEngine" class="org.thymeleaf.spring3.SpringTemplateEngine">
<property name="templateResolvers">
<set>
<ref bean="emailTemplateResolver" />
<ref bean="webTemplateResolver" />
</set>
</property>
</bean>
<!-- THYMELEAF: View Resolver - implementation of Spring's ViewResolver interface -->
<!-- (we would not need this if our app was not web) -->
<bean id="viewResolver" class="org.thymeleaf.spring3.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine" />
<property name="characterEncoding" value="UTF-8" />
</bean>
<import resource="daoContext.xml"/>
Here emailService:
final WebContext ctx = new WebContext(request,response, request.getServletContext(), locale);
//.....
// Create the HTML body using Thymeleaf
final String htmlContent = this.templateEngine.process("email-inlineimage.html", ctx);
message.setText(htmlContent, true /* isHtml */);
And Error:
org.thymeleaf.exceptions.TemplateInputException: Error resolving template "email-
inlineimage.html", template might not exist or might not be accessible by any of the
configured Template Resolvers
org.thymeleaf.TemplateRepository.getTemplate(TemplateRepository.java:245)
org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1104)
org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1060)
org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1011)
org.thymeleaf.TemplateEngine.process(TemplateEngine.java:924)
org.thymeleaf.TemplateEngine.process(TemplateEngine.java:898)
com.podium.italia.service.EmailService.sendMailWithInlineImages(EmailService.java:112)
I can't spot error in your servlet-context.xml so problem must be buried somewhere else (are you sure you have template file on classpath exactly at mail/email-inlineimage.html?). I'm providing working example as whole project (since it's overkill to paste everything to code samples here) which you can import to STS and run.
Spring Thymeleaf Mailing
Related
I have this error when run spring project by -cp
java -cp "parser.jar" hu.daniel.hari.learn.spring.orm.main.SpringOrmMain
Exception in thread "main" org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/p]
Offending resource: class path resource [spring.xml]
at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:70)
at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85)
at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:80)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.error(BeanDefinitionParserDelegate.java:309)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.decorateIfRequired(BeanDefinitionParserDelegate.java:1464)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.decorateBeanDefinitionIfRequired(BeanDefinitionParserDelegate.java:1440)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.decorateBeanDefinitionIfRequired(BeanDefinitionParserDelegate.java:1428)
My beans.xml
<?xml version="1.0" encoding="UTF-8"?>
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
">
<!-- Scans the classpath for annotated components that will be auto-registered
as Spring beans -->
<context:component-scan base-package="hu.daniel.hari.learn.spring" />
<!-- Activates various annotations to be detected in bean classes e.g: #Autowired -->
<context:annotation-config />
<!-- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.hsqldb.jdbcDriver" /> <property
name="url" value="jdbc:hsqldb:mem://productDb" /> <property name="username"
value="sa" /> <property name="password" value="" /> </bean> -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432/newparser" />
<property name="username" value="postgres" />
<property name="password" value="postgres" />
<!--<property name="socketTimeout" value="10"/> -->
<property name="connectionProperties">
<props>
<prop key="socketTimeout">10</prop>
</props>
</property>
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:packagesToScan="hu.daniel.hari.learn.spring.orm.model"
p:dataSource-ref="dataSource">
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="true" />
<property name="showSql" value="true" />
</bean>
</property>
</bean>
<!-- Transactions -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
Add namespace for the shorthand property (p:)
<beans
...
xmlns:p="http://www.springframework.org/schema/p"
I'm trying to use hsqldb in file mode with spring and hibernate,
but the the database is not being initialized and i'm getting the following error message:
2015-03-12 23:58:35,542 FATAL [hsqldb.db.HSQLDB4C0FFF0D08.ENGINE]: could not reopen database
org.hsqldb.HsqlException: Database lock acquisition failure: lockFile: org.hsqldb.persist.LockFile#6602b8e7[file =C:\User\db".lck, exists=false, locked=false, valid=false, ] method: openRAF reason: java.io.FileNotFoundException: C:\User\db".lck (The filename, directory name, or volume label syntax is incorrect)
My spring configuration is as following:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
<tx:annotation-driven />
<context:component-scan base-package="org.oss.orm" />
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>db.properties</value>
</property>
</bean>
<!-- data source -->
<bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource">
<property name="driverClass" value="${jdbc.driverClassName}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="partitionCount" value="3" />
<property name="acquireIncrement" value="10" />
<property name="maxConnectionsPerPartition" value="60" />
<property name="minConnectionsPerPartition" value="20" />
</bean>
<jdbc:initialize-database data-source="dataSource">
<jdbc:script location="classpath:scripts/create-table-if-not-exists" />
</jdbc:initialize-database>
<!-- Session Factory -->
<bean id="sessionFactory" name="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="packagesToScan" value="org.oss.beans"></property>
<property name="hibernateProperties">
<props>
<prop key="dialect">org.hibernate.dialect.HSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<!-- Create Tables if does not exist -->
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>org.oss.beans.Property</value>
<value>org.oss.beans.PropertyImage</value>
</list>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory">
</bean>
With the seperate properties file:
jdbc.driverClassName=org.hsqldb.jdbcDriver
jdbc.url=jdbc:hsqldb:file:#{systemProperties['user.home']}\\db"
jdbc.dialect=org.hibernate.dialect.HSQLDialect
jdbc.username=sa
jdbc.password=
What changes needs to be made for the db to be initialized?
I'm trying to implement a webservice with Spring 3.0 + JAX-WS (METRO), but I get an error when starting the server...
org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 148 in XML
document from ServletContext resource [/WEB-INF/applicationContext.xml] is invalid;
nested exception is org.xml.sax.SAXParseException; lineNumber: 148; columnNumber: 64;
cvc-complex-type.2.4.c:The matching wildcard is strict, but no declaration can be found
for element 'wss:binding'
.
I just need to inject spring annotations (#Autowired and #PersistenceContext) inside my webservices so I'm using wss:binding...
My applicationContext.xml is...
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:ws="http://jax-ws.java.net/spring/core"
xmlns:wss="http://jax-ws.java.net/spring/servlet"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://jax-ws.java.net/spring/core
http://jax-ws.java.net/spring/core.xsd
http://jax-ws.java.net/spring/servlet
http://jax-ws.java.net/spring/servlet.xsd">
<context:annotation-config />
<context:component-scan base-package="br.com.mmm.application" />
<mvc:annotation-driven />
<bean id="placeHolderConfig"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreResourceNotFound" value="false" />
<property name="ignoreUnresolvablePlaceholders" value="false" />
<property name="location" value="classpath:mvsaudews.properties" />
</bean>
<!-- Configuracao do DataSource para o pool de conexões Oracle -->
<bean id="dataSource" class="oracle.jdbc.pool.OracleDataSource"
destroy-method="close">
<property name="URL" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="connectionCachingEnabled" value="true" />
<property name="connectionCacheProperties">
<value>
MinLimit = 5
MaxLimit = 60
InactivityTimeout = 600
TimeToLiveTimeout = 600
PropertyCheckInterval = 180
InitialLimit = 5
MaxStatementsLimit = 5000
ValidateConnection = true
</value>
</property>
</bean>
<!-- Entity Manager do JPA 2.0 -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<!-- <property name="persistenceUnitName" value="mvsaudews" /> -->
<!-- <property name="persistenceXmlLocation" value="/META-INF/persistence.xml"/> -->
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="br.com.mmm.application.model" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.connection.driver_class">${jdbc.driverClassName}</prop>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.default_schema">${jdbc.default_schema}</prop>
<prop key="hibernate.archive.autodetection">${hibernate.autodetection}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<prop key="use_sql_comments">true</prop>
<prop key="hibernate.query.substitutions">${hibernate.substitutions}</prop>
</props>
</property>
</bean>
<!-- Gerenciador de transacoes by JPA -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- the transactional advice (what 'happens'; see the <aop:advisor/> bean below) -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!-- the transactional semantics... -->
<tx:attributes>
<!-- all methods starting with 'get' are read-only -->
<tx:method name="get*" read-only="true" />
<!-- other methods use the default transaction settings (see below) -->
<tx:method name="*" />
</tx:attributes>
</tx:advice>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- DataSourceManager -->
<bean id="dataSourceManager" class="br.com.mmm.library.DataSourceManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- WebServices -->
<wss:binding url="/services/v/verificaElegibilidade">
<wss:service>
<ws:service bean="#verificaElegibilidade"/>
</wss:service>
</wss:binding>
<bean id="verificaElegibilidade" class="br.com.mmm.webservices.v.verificaElegibilidade"/>
Thanks for any help
Try this:
xmlns:ws="http://jax-ws.dev.java.net/spring/core"
xmlns:wss="http://jax-ws.dev.java.net/spring/servlet"
I'm using Spring MVC with Hibernate. I'm trying to use two different databases (on two different servers). One is MySQL and the other is DB2.
Here is my dispatcher-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- Load JDBC Properties -->
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- Enable Annotations (MVC and Hibernate Transactions) -->
<context:component-scan base-package="com.example" />
<mvc:annotation-driven />
<tx:annotation-driven transaction-manager="hibernateTransactionManager" />
<!-- Tell Spring where to find static files and not use a controller -->
<mvc:resources mapping="/css/**" location="/WEB-INF/css/*" />
<mvc:resources mapping="/js/**" location="/WEB-INF/js/*" />
<!-- Create a ViewResolver -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Create a DataSource for MySQL -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${mysql.database.driver}" />
<property name="url" value="${mysql.database.url}" />
<property name="username" value="${mysql.database.user}" />
<property name="password" value="${mysql.database.password}" />
</bean>
<!-- Create a DataSource for DB2 -->
<bean id="db2DataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${db2.database.driver}" />
<property name="url" value="${db2.database.url}" />
<property name="username" value="${db2.database.user}" />
<property name="password" value="${db2.database.password}" />
</bean>
<!-- Create a Session Factory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.example.model.entities.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${mysql.hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${mysql.hibernate.show_sql}</prop>
<prop key="hibernate.c3p0.min_size">${mysql.hibernate.c3p0.min_size}</prop>
<prop key="hibernate.c3p0.max_size">${mysql.hibernate.c3p0.max_size}</prop>
<prop key="hibernate.c3p0.timeout">${mysql.hibernate.c3p0.timeout}</prop>
<prop key="hibernate.c3p0.max_statements">${mysql.hibernate.c3p0.max_statements}</prop>
<prop key="hibernate.c3p0.idle_test_period">${mysql.hibernate.c3p0.idle_test_period}</prop>
</props>
</property>
</bean>
<bean id="sessionFactoryDB2" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="db2DataSource" ref="db2DataSource" />
<property name="annotatedClasses">
<list>
<value>com.example.model.entities.Transfer</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${db2.hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${db2.hibernate.show_sql}</prop>
<prop key="hibernate.c3p0.min_size">${db2.hibernate.c3p0.min_size}</prop>
<prop key="hibernate.c3p0.max_size">${db2.hibernate.c3p0.max_size}</prop>
<prop key="hibernate.c3p0.timeout">${db2.hibernate.c3p0.timeout}</prop>
<prop key="hibernate.c3p0.max_statements">${db2.hibernate.c3p0.max_statements}</prop>
<prop key="hibernate.c3p0.idle_test_period">${db2.hibernate.c3p0.idle_test_period}</prop>
</props>
</property>
</bean>
<!-- Create a Transaction Manager -->
<bean id="hibernateTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
<property name="sessionFactoryDB2" ref="sessionFactoryDB2" />
</bean>
</beans>
But when I run I get this error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transfersController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.example.model.service.UserService....
I am using #Autowired in my controllers/models. So it makes sense that it doesn't know which bean to use to autowire. But how do I solve this?
Thanks
<bean id="sessionFactoryDB2" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="db2DataSource" ref="db2DataSource" />
<property name="annotatedClasses">
I don't think there is a property named db2DataSource in AnnotationSessionFactoryBean. That may be one of the reason it is failing. It should be <property name="dataSource" ref="db2DataSource" /> instead.
I think problem does not exist with your dataSources. To autowire service classes you need to use #Service(preferred for service layer classes) stereotype annotation.
You also need to scan these annotated classes using component scan which I didn't see in your posted xml.
<context:component-scan base-package="com.example, com.example.model.service" />
We are working on a Spring based Web application where the key to the business is high availability. Hibernate is the ORM and MySQL is the DB that is used. Our architecture forces us to have the following mechanism.
The Webapp first tries to connect to the primary MySQL server.
If that fails, it connects to the Secondary MySQL server, which is mostly out of sync with the data.
The webapp needs to know which MySQL Server it is connected to, since we want to notify the user when he is using the secondary server.
As soon as the connection re-establishes with the primary, the connected has to be switched from secondary to primary.
I am stuck at the very first phase. I am unable find out how to direct Spring/Hibernate to use multiple DB Servers.
Here is the current config file (removing the unwanted stuff):
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<context:annotation-config />
<context:component-scan base-package="com.smartshop" />
<bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/primarydb" />
<property name="username" value="username" />
<property name="password" value="password" />
<property name="maxIdle" value="10" />
<property name="maxActive" value="100" />
<property name="maxWait" value="10000" />
<property name="validationQuery" value="select 1" />
<property name="testOnBorrow" value="false" />
<property name="testWhileIdle" value="true" />
<property name="timeBetweenEvictionRunsMillis" value="1200000" />
<property name="minEvictableIdleTimeMillis" value="1800000" />
<property name="numTestsPerEvictionRun" value="5" />
<property name="defaultAutoCommit" value="false" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>/WEB-INF/hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">false</prop>
</props>
</property>
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean
class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor"
name="openSessionInViewInterceptor">
<property name="sessionFactory" ref="sessionFactory"></property>
<property name="flushMode">
<bean
id="org.springframework.orm.hibernate3.HibernateAccessor.FLUSH_AUTO"
class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean" />
</property>
</bean>
<bean id="handlerMapping"
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<list>
<ref bean="localeChangeInterceptor" />
<ref bean="openSessionInViewInterceptor" />
</list>
</property>
</bean>
Is there a way to define Spring to connect to a backup datasource when the primary datasource is inaccessible?
if you configure your datasource as a jndi datasource you can use the following configuration
<bean id="dataSource"
class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" ref="datasourceJNDIName" />
<property name="defaultObject" ref="fallBackDataSource" />
</bean>
<!-- fall back datasource if JNDI look up of main datasource fails -->
<bean id="fallBackDataSource"
class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" ref="datasourceJNDIName-2" />
</bean>
This kind of tricks have to be done on MySQL side not on the webapp. MySQL cluster for instance can handle this.
More infos here:
-http://www.mysql.com/products/cluster/
-http://en.wikipedia.org/wiki/MySQL_Cluster
UPDATE:
Ok, so, have a look here -> org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource . Build a custom implementation that override the method getConnection() and getConnection(String username, String password). Surroud them by catching SQLException, and if occurs, choose the other datasource.