No unique bean of type [javax.persistence.EntityManagerFactory] is defined: expected single bean but found 0: - spring

I use Spring and Spring data for the system that I am developing. The following is the config file.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<context:component-scan base-package="co.infovilla.vendor" />
<context:component-scan base-package="co.infovilla.vendor.repositories" />
<context:component-scan base-package="co.infovilla.vendor.services" />
<jpa:repositories base-package="co.infovilla.vendor.repositories" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/vendordb" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
</beans>
When I access it using the following code I get exceptions.
public static void main(String[] args) {
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext("application-context.xml");
ProductService productService = ctx.getBean(ProductService.class);
Product product = new Product();
product.setName("Phone");
product.setPrice(500000);
productService.save(product);
}
The exceptions are:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productService': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productRepository': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [javax.persistence.EntityManagerFactory] is defined: expected single bean but found 0:
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:306)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:607)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:925)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:472)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at co.infovilla.vendor.main.App.main(App.java:11)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productRepository': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [javax.persistence.EntityManagerFactory] is defined: expected single bean but found 0:
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:343)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:442)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:416)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:550)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:155)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:92)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:303)
... 13 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [javax.persistence.EntityManagerFactory] is defined: expected single bean but found 0:
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findDefaultEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:538)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:497)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.resolveEntityManager(PersistenceAnnotationBeanPostProcessor.java:659)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.getResourceToInject(PersistenceAnnotationBeanPostProcessor.java:632)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:164)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:92)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:340)
... 26 more
As far as I know I don't need to configure the entity manager factory when using JPA the way I am using it. What might have gone wrong?

<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
This isn't configuring an EntityManagerFactory but a SessionFactory. To configure an EntityManagerFactory use a LocalContainerEntityManagerFactoryBean. See here for more information on how to setup JPA with Spring.
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="datasource"/>
<property name="packagesToScan" value="[package-containing-your-#Entities]"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="generateDdl" value="true" />
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
</bean>
</property>
</bean>
You probably also want to use the specific MySQL5InnoDBDialect instead of the plain MysqlDialect.

Related

Repository Error - FactoryBean which is currently in creation returned null from getObject. in Atomikos distributed transaction

I am currently following tutorial of atomikos for distributed transaction using xml configuration. I get error in repository level with message factory bean which is currently in creation returned null from getObject. I think there is no any circular dependency in beans and database connection is also fine. When I removed repository from service implementation then there is no error.
Error i get in console
Error creating bean with name 'auctionServiceRequired_TX' defined in class path resource [spring-sender-mysql.xml]: Cannot resolve reference to bean 'auctionTarget' while setting bean property 'target'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'auctionTarget': Unsatisfied dependency expressed through field 'quoteRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'quoteRepository': Cannot resolve reference to bean 'jpaMappingContext' while setting bean property 'mappingContext'; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'jpaMappingContext': FactoryBean which is currently in creation returned null from getObject
spring-sender-mysql.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/springa-jpa.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd ">
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>application.properties</value>
</property>
</bean>
<bean id="datasourceAtomikos-01"
class="com.atomikos.jdbc.AtomikosDataSourceBean" init-method="init" destroy-method="close">
<property name="uniqueResourceName"><value>JDBC-1</value></property>
<property name="xaDataSource"><ref bean="xaDataSourceMySQL-01" /></property>
<property name="xaProperties">
<props>
<prop key="maxPoolSize">4</prop>
<prop key="uniqueResourceName">xads1</prop>
</props>
</property>
<property name="poolSize"><value>4</value></property>
</bean>
<bean id="xaDataSourceMySQL-01" class="com.mysql.cj.jdbc.MysqlXADataSource">
<property name="url">
<value>${jdbc.url}</value>
</property>
<property name="pinGlobalTxToPhysicalConnection"><value>true</value></property>
<property name="user"><value>${jdbc.username}</value></property>
<property name="password"><value>${jdbc.password}</value></property>
</bean>
<bean id="atomikosTransactionManager" class="com.atomikos.icatch.jta.UserTransactionManager" init-method="init" destroy-method="close">
<property name="forceShutdown"><value>true</value></property>
</bean>
<bean id="atomikosUserTransaction" class="com.atomikos.icatch.jta.UserTransactionImp">
<property name="transactionTimeout"><value>300</value></property>
</bean>
<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="transactionManager"><ref bean="atomikosTransactionManager" /></property>
<property name="userTransaction"><ref bean="atomikosUserTransaction" /></property>
</bean>
<bean id="springJtaPlatformAdapter" class="io.trustaml.AtomikosJtaPlatform">
<property name="jtaTransactionManager" ref="transactionManager" />
</bean>
<bean id="hibernateJpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
<bean id="quoteEntityManager" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="datasourceAtomikos-01"/>
<property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.transaction.jta.platform">io.trustaml.AtomikosJtaPlatform</prop>
<prop key="javax.persistence.transactionType">JTA</prop>
</props>
</property>
<property name="packagesToScan" value="io.trustaml.model"/>
<property name="persistenceUnitName" value="quotePersistenceUnit" />
</bean>
<jpa:repositories base-package="io.trustaml.repository" entity-manager-factory-ref="quoteEntityManager"/>
<!-- Error in creating this bean -->
<bean id="auctionTarget" class= "io.trustaml.service.AuctionServiceImpl">
</bean>
<bean id="auctionServiceRequired_TX" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager"><ref bean="transactionManager" /></property>
<property name="target"><ref bean="auctionTarget" /></property>
<property name="transactionAttributes">
<props>
<prop key="confirm*">PROPAGATION_REQUIRED, -QuotesConfirmRollbackException, +QuotesNoRollbackException</prop>
<prop key="find*">PROPAGATION_SUPPORTS, readOnly</prop>
</props>
</property>
</bean>
<bean id="auctionServiceRequiresNew_TX" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager"><ref bean="transactionManager" /></property>
<property name="target"><ref bean="auctionTarget" /></property>
<property name="transactionAttributes">
<props>
<prop key="confirm*">PROPAGATION_REQUIRES_NEW, -QuotesConfirmRollbackException, +QuotesNoRollbackException</prop>
<prop key="find*">PROPAGATION_SUPPORTS, readOnly</prop>
</props>
</property>
</bean>
</beans>
Repository
public interface QuoteRepository extends JpaRepository<Quote, Long> {
List<Quote> findByStatus(String status);
}
Service Implementing repository
#Service
public class AuctionServiceImpl implements AuctionService{
private static final Logger LOGGER = LoggerFactory.getLogger(AuctionServiceImpl.class);
private static volatile boolean flipFlop = false;
#Autowired
private QuoteRepository quoteRepository;
// other business logic goes here
}

Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Cannot resolve reference to bean 'xaDataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'xaDataSource' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'xaDataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'driverClassName' of bean class [org.postgresql.xa.PGXADataSource]: Bean property 'driverClassName' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1481)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1226)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1054)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:829)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5068)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5584)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:899)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:875)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:652)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1091)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1980)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
<?xml version="1.0" encoding="UTF-8"?>
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">
<bean id="requestHandler" class="org.dejach.marketServer.requesthandler.RequestHandler" init-method="init">
<property name="factory" ref="marketApiFactory"></property>
</bean>
<bean id="RequestProcessor" class="org.dejach.marketServer.processor.RequestProcessor">
<property name="handler" ref="requestHandler" />
</bean>
<bean id="marketApiFactory" class="org.dejach.marketServer.processor.MarketApiFactory">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>WEB-INF/marketApi.properties</value>
</property>
<property name="nullValue" value="#null" />
</bean>
<bean id="properties"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="WEB-INF/marketApi.properties" />
</bean>
<bean id="dataSource" class="org.postgresql.xa.PGXADataSource">
<!-- <property name="pinGlobalTxToPhysicalConnection" value="true" /> -->
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="${jdbcUrl}" />
<property name="user" value="${username}" />
<property name="password" value="${password}" />
</bean>
<!-- configure an Atomikos JTA-aware datasource -->
<bean id="xaDataSource" class="com.atomikos.jdbc.AtomikosDataSourceBean"
init-method="init" destroy-method="close">
<property name="uniqueResourceName" value="xaDatasource" />
<property name="xaDataSource" ref="dataSource" />
<property name="poolSize" value="${poolSize}" />
</bean>
<!-- http://fogbugz.atomikos.com/default.asp?community.6.702.5 -->
<bean id="userTransactionService" class="com.atomikos.icatch.config.UserTransactionServiceImp"
init-method="init" destroy-method="shutdownForce">
<constructor-arg>
<props>
<prop key="com.atomikos.icatch.log_base_name">${com.atomikos.icatch.log_base_name}</prop>
<prop key="com.atomikos.icatch.log_base_dir">${com.atomikos.icatch.log_base_dir}</prop>
<prop key="com.atomikos.icatch.max_timeout">3600000</prop>
</props>
</constructor-arg>
</bean>
<bean id="atomikosTransactionManager" class="com.atomikos.icatch.jta.UserTransactionManager"
init-method="init" destroy-method="close" depends-on="userTransactionService">
<property name="forceShutdown" value="false" />
<property name="startupTransactionService" value="true" />
</bean>
<bean id="atomikosUserTransaction" class="com.atomikos.icatch.jta.J2eeUserTransaction">
<property name="transactionTimeout" value="${transactionTimeout}" />
</bean>
<bean id="transactionManager"
class="org.springframework.transaction.jta.JtaTransactionManager"
depends-on="atomikosTransactionManager,atomikosUserTransaction">
<property name="transactionManager" ref="atomikosTransactionManager" />
<property name="userTransaction" ref="atomikosUserTransaction" />
<property name="allowCustomIsolationLevels" value="true" />
</bean>
<bean id="jpaVendor"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="${showSql}" />
<property name="databasePlatform" value="${databasePlatform}" />
<property name="generateDdl" value="${generateDdl}" />
<property name="database" value="${database}" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="xaDataSource" />
<property name="packagesToScan" value="${marketPackage}" />
<property name="jpaVendorAdapter" ref="jpaVendor" />
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
</props>
</property>
</bean>
username=postgres
password=$$$$$$$
hibernate.hbm2ddl.auto=create
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
# package scan for entities
marketPackage=org.dejach
transactionTimeout=300
showSql=true
#databasePlatform=org.hibernate.dialect.MySQL5InnoDBDialect
databasePlatform=org.hibernate.dialect.PostgreSQLDialect
#database=org.springframework.orm.jpa.vendor.Database.MYSQL
#database=MYSQL
database=POSTGRESQL
generateDdl=false
poolSize=30
#XA datasource
#XADataSource=${mysqlDataSource}
XADataSource=${postgresqlDataSource}
#mysqlDataSource=com.mysql.jdbc.jdbc2.optional.MysqlXADataSource
postgresqlDataSource=org.postgresql.xa.PGXADataSource
H2xadatasource=org.h2.jdbcx.JdbcDataSource
postgresqlUrl = jdbc:postgresql://localhost:5432/ethiopianMarketdb
H2url=jdbc:h2:mem:testdb;MODE=MySQL;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
jdbcUrl=${postgresqlUrl}
blobFieldName=xmlData
#Atomikus properties
#see http://www.atomikos.com/Documentation/JtaProperties com.atomikos.icatch.service=com.atomikos.icatch.standalone.UserTransactionServiceFactory
com.atomikos.icatch.console_file_name
#Specifies the console log level. Defaults to WARN. Should be one of: WARN, INFO or DEBUG.
com.atomikos.icatch.log_base_name=tmlog
com.atomikos.icatch.log_base_dir=target
#com.atomikos.icatch.log_base_dir=/transactionLogs/
#com.atomikos.icatch.tm_unique_name=
com.atomikos.icatch.max_timeout=3600000
I don't see a setter setDriverClassName(..) in following class
https://jdbc.postgresql.org/documentation/publicapi/org/postgresql/xa/PGXADataSource.html
So, it make sense to remove following property from xaDataSource and try once again
<property name="driverClassName" value="org.postgresql.Driver" />
BTW, I don't any setUrl either, so you should review the logic of creating your bean.
Here is the list of available setters:
setCompatible
setDatabaseName
setLoginTimeout
setLogLevel
setLogWriter
setPassword
setPortNumber
setPrepareThreshold
setProtocolVersion
setServerName
setSocketTimeout
setSsl
setSslfactory
setTcpKeepAlive
setUnknownLength
setUser
writeBaseObject

How to scan hibernate entities package in struts2,spring3 application instead of using cfg.xml

I know this question may be a duplicate. I saw the link
[How to scan packages for Hibernate entities instead of using hbm.xml?
In my application using Struts2,hibernate3,and spring3
though I successfully removed the xml file for DAO and Service via <context:component-scan> in applicationcontext.xml, when I tried to use
<property name="packagesToScan" value="com.iris.admin"></property> it throws some typeNotMatchException and `Session factory BeanCreationException
Below is My Configuration File
...............hibernate.cfg.xml............................................
<hibernate-configuration>
<session-factory>
<mapping class="com.vaib.admin.languageMaster.bean.Menu" />
<mapping class="com.vaib.admin.companyType.bean.CompanyType" />
<mapping class="com.vaib.admin.companyType.bean.CompanyTypeModified" />
</session-factory>
</hibernate-configuration>
applicationcontext-DataSource.xml
<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"
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">
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="maxConnectionAge" value="${jdbc.maxConnectionAge}" />
<property name="checkoutTimeout" value="${jdbc.checkoutTimeout}" />
<property name="idleConnectionTestPeriod" value="${jdbc.idleConnectionTestPeriod}" />
<property name="acquireIncrement" value="${jdbc.acquireIncrement}" />
<property name="acquireRetryAttempts" value="${jdbc.acquireRetryAttempts}" />
<property name="initialPoolSize" value="${jdbc.initialPoolSize}" />
<property name="minPoolSize" value="${jdbc.minPoolSize}" />
<property name="maxPoolSize" value="${jdbc.maxPoolSize}" />
<property name="maxIdleTime" value="${jdbc.maxIdleTime}" />
<property name="autoCommitOnClose" value="${jdbc.autoCommitOnClose}" />
<property name="unreturnedConnectionTimeout" value="${jdbc.unreturnedConnectionTimeout}" />
<property name="debugUnreturnedConnectionStackTraces" value="${jdbc.debugUnreturnedConnectionStackTraces}"/>
<property name="driverClass" value="${jdbc.driverClassName}" />
<property name="jdbcUrl" value="${jdbc.db_url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="maxStatements" value="${jdbc.maxStatements}" />
<property name="testConnectionOnCheckout" value="${jdbc.testConnection}" />
<property name="maxStatementsPerConnection"value="${jdbc.maxStatementsPerConnection}" />
</bean>
application-Context.xml
<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"
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">
<context:annotation-config />
<!-- <context:component-scan base-package="com.iris.webservices.controller"></context:component-scan> -->
<context:component-scan base-package="com.vaib"></context:component-scan>
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
<property name="preparerFactoryClass" value="org.springframework.web.servlet.view.tiles2.SpringBeanPreparerFactory" />
</bean>
<!-- <import resource="applicationContext-datasource.xml" /> -->
<import resource="applicationPersistence.xml" />
<import resource="applicationService.xml" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation">
<value>/webapp/WEB-INF/applicationContext-datasource.xml</value>
</property>
<!-- <property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property> -->
<property name="packagesToScan" value="com.vaib.admin"></property>
<!-- <property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property> -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.default_schema">ifileprod</prop>
<!-- Local DB -->
<!-- <prop key="hibernate.default_schema">iFileProd</prop> -->
<prop key="hibernate.connection.autoReconnect">true</prop>
<prop key="hibernate.connection.autoReconnectForPools">true</prop>
</props>
</property>
</bean>
<!-- <bean id="subCategory" class="com.iris.admin.subcategory.bean.SubCategory"></bean> -->
<!-- <bean id="menuPreparer" class="com.iris.admin.menuMngt.preparer.MenuViewPreparer"></bean> -->
<!-- <bean id="applicationStartListener" class="com.iris.listener.ApplicationStartListener"></bean> -->
<!-- <bean id="applicationClosedListener" class="com.iris.listener.ApplicationClosedListener"></bean> -->
</beans>
I have following Exception
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'categoryDao': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.vaib.admin.category.dao.CategoryDao.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'dataSource' is defined
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4729)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5167)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.vaib.admin.category.dao.CategoryDao.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'dataSource' is defined
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:502)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:282)
... 22 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'dataSource' is defined
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1325)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1086)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:844)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:786)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:703)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:474)
... 24 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'dataSource' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:527)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1083)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:274)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:322)
... 37 more
I couldn't understand why it comes while in seperate application it works fine when i am using packageTOScan attribute
Thanks in advance.
The root cause is :
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'dataSource' is defined
You have commented line
<!-- <import resource="applicationContext-datasource.xml" /> -->
Remove the comment and it should work fine

I'm getting error while integrating spring and hibernate

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'studentManager' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'studentDao' while setting bean property 'studentDao';
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'studentDao' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory';
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Initialization of bean failed;
nested exception is java.lang.NoClassDefFoundError: javax/transaction/TransactionManager
applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"
default-lazy-init="true">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/Java2all"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>Student.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">false</prop>
</props>
</property>
</bean>
<bean id="studentDao" class="com.dao.impl.StudentDaoHibernate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="studentManager" class="com.manager.StudentManagerImpl">
<property name="studentDao" ref="studentDao" />
</bean>
</beans>
student.xml
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name ="com.springhibnernate.Student" table="Student">
<id name="id" type="java.lang.Long">
<generator class="native"/>
</id>
<property name="name" type="string">
<column name="name" length="40"/>
</property>
</class>
</hibernate-mapping>
There is a good chance you are missing "JTA-X.X.jar" in your classpath.

org.springframework.beans.factory.BeanCreationException: Error while mapping Spring with context datasource

This is my spring context file
<!-- <context:property-placeholder location="classpath:jdbc.properties" />-->
<context:component-scan base-package="com.max.premcalc" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager" />
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<jee:jndi-lookup id="dataSource" jndi-name="jdbc/inquizzitiveds"/>
<!-- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean> -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.max.premcalc.domain.PremiumCalc</value>
<value>com.max.premcalc.domain.Inputparam</value>
<value>com.max.premcalc.domain.RiderInput</value>
<value>com.max.premcalc.domain.Rider</value>
<value>com.max.premcalc.domain.Product</value>
<value>com.max.premcalc.domain.Products</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</property>
</bean>
<bean id="hibernateTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="MainController" class="com.max.premcalc.controller.MainController" />
<bean id = "calcDao" class="com.max.premcalc.dao.CalcDaoImpl"/>
<bean id = "calcService" class="com.max.premcalc.service.CalcServiceImpl"/>
<bean id = "inputparam" class = "com.max.premcalc.domain.Inputparam"/>
But I'm getting this error :
Injection of autowired dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not autowire field: private
com.max.premcalc.service.CalcService com.max.premcalc.controller.MainController.calcService; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'calcServiceImpl': Injection
of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:
Could not autowire field: com.max.premcalc.dao.CalcDao com.max.premcalc.service.CalcServiceImpl.calcDao; nested
exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDao':
Injection of autowired dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void
com.max.premcalc.dao.CalcDaoImpl.setSessionFactory(org.hibernate.SessionFactory); nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in
ServletContext resource [/WEB-INF/dispatcher-servlet.xml]: Invocation of init method failed; nested exception is
org.hibernate.HibernateException: Hibernate Dialect must be explicitly set
You need to set the property
hibernate.dialect
In the hibernate (persistence.xml or bean declaration) configuration, the value depends on your database, for example:
Postgres: org.hibernate.dialect.PostgreSQL82Dialect
Oracle: org.hibernate.dialect.Oracle10gDialect
All posible options are listen here
For example, a sample persistence.xml looks like:
<persistence-unit>
...
<properties>
...
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
...
</properties>
</persistence-unit>
Please, check if your properties file have the key hibernate-dialect
The stacktrace is pretty clear
org.hibernate.HibernateException: Hibernate Dialect must be explicitly set
Apparently hibernate cannot use the metadata to retrieve the type of database to use, as a result one must configure the hibernate dialect explicitly.

Resources