Spring + GWT UnsatisfiedDependencyException - java

I looked at almost every topic about org.springframework.beans.factory.UnsatisfiedDependencyException but I can't find a solution for my problem. My service looks like this:
#Service
public class PacientService {
#Resource
private PacientDAO dao;
#Resource
private PacientModelTransformer transformer;
public PacientService() {
}
#Autowired
public PacientService(PacientDAO dao, PacientModelTransformer transformer) {
this.dao = dao;
this.transformer = transformer;
}
public PacientDTO getPacientById(Long pacientId) {
return transformer.toDTO(dao.readByPrimaryKey(pacientId));
}
}
<context:annotation-config />
<context:component-scan base-package="pl.arprojects.dietetyk" />
<tx:annotation-driven transaction-manager="transactionManager" />
<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/d2" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
<property name="database" value="MYSQL" />
</bean>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<hades:dao-config base-package="pl.arprojects.dietetyk.api.domian" />
This is my applicationContext.xml. I really dont know why I've got an exception like this:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'pacientService' defined in file [D:\Dietetyk\Dietetyk\target\dietetyk-1.0.0-SNAPSHOT\WEB-INF\classes\pl\arprojects\dietetyk\server\service\PacientService.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [pl.arprojects.dietetyk.api.dao.PacientDAO]: : No matching bean of type [pl.arprojects.dietetyk.api.dao.PacientDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [pl.arprojects.dietetyk.api.dao.PacientDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
No, this DAO hasnt got any subclasses and looks exactly like this:
#Repository
public interface PacientDAO extends GenericDao<Pacient, Long> {
#Query("Select * from dietetyk_pacients where name = :name")
public Pacient getByName(#Param("name") String name);
#Query("")
public void deleteByPrimaryKey(#Param("id") long id);
}
Extends GenericDao from Hades Synyx
<?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:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:hades="http://schemas.synyx.org/hades"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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://schemas.synyx.org/hades http://schemas.synyx.org/hades/hades.xsd">
<context:annotation-config />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
<property name="database" value="MYSQL" />
</bean>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<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/d2" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<hades:dao-config base-package="pl.arprojects.dietetyk.api.domian" />
applicationContext.xml

Try #Repository or #Component annotation for all DAO classes including sub-classes of base DAO and no need to define a name in annotation.
Dependencies are resolved by type.

Related

Dispacter Servelt xml file

I am working on project with Spring mvc and i want to use jpa features as well.
I have an 3 entity classes, their corresponding repository interfaces. I have their autowired objects in common service class. However I am facing issues while creating bean for this service class object which is used in controller.
The 3 model class are User, Appointment and Notification.
The repository interface extends CRUDRepository interface.
Service class :
#Service
public class EHealthService
{
#Autowired
UserRepository uRepo;
#Autowired
AppointmentRepository aRepo;
#Autowired
NotificationRepository nRepo;
public void registerUser(User u)
{
uRepo.save(u);
}
public boolean login(User u)
{
if(uRepo.findByemail(u.getEmail())!=null)
return true;
else
return false;
}
public List<User> getDoctorList()
{
return uRepo.findByisdoctor(true);
}
// some more functions
}
Controller class:
#Controller
public class EHealthController
{
#Autowired
EHealthService eservice;
//Some code
}
ehealth-dispacter-servlet.xml file:
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation=
"http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<context:component-scan base-package="com.cl3.controller" />
<context:component-scan base-package="com.cl3.model" />
<context:component-scan base-package="com.cl3.service" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="generateDdl" value="true"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
<property name="packagesToScan" value="com.cl3.model"/>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
<jpa:repositories base-package="com.cl3.model"/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432/cl3" />
<property name="username" value="ucan" />
<property name="password" value="ucan" />
</bean>
<bean id="eservice" class="com.cl3.service.EHealthService">
<property name="uRepo" ref="uRepo"></property>
<property name="nRepo" ref="nRepo"></property>
<property name="aRepo" ref="aRepo"></property>
</bean>
<bean id="uRepo" class="com.cl3.model.UserRepository">
</bean>
<bean id="nRepo" class="com.cl3.model.NotificationRepository">
</bean>
<bean id="aRepo" class="com.cl3.model.AppointmentRepository">
</bean>
It says the class is an interface.
What will be the bean for eservice object and to enable jpa in dispacter servel xml file?
Thank you.
If you are using spring xml based configuration then add below bean's to configuration file :
<bean id="entityManagerFactoryBean" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- This makes /META-INF/persistence.xml is no longer necessary -->
<property name="packagesToScan" value="com.howtodoinjava.demo.model" />
<!-- JpaVendorAdapter implementation for Hibernate EntityManager.
Exposes Hibernate's persistence provider and EntityManager extension interface -->
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">validate</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
</props>
</property>
<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/test" />
<property name="username" value="root" />
<property name="password" value="password" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactoryBean" />
Register component scanning by adding this binding annotation in xml file :
<context:component-scan base-package="com.mycompany.projectname.demo" />
If your project is spring mvc the add below binding annotation to xl file
<!-- This allow for dispatching requests to Controllers -->
<mvc:annotation-driven />
For declarative transaction management add below piece in xml file.
<tx:annotation-driven />
Basically you no need to add service bean in xml configuration file if you are enabled component scanning feature in spring.
Add required dependencies to integrate jpa with spring.
Refer this link will help you more :
https://howtodoinjava.com/jpa/spring-hibernate-jpa-configuration-example/

Removing Data Source Connection Spring + JPA

Hy there folks, i'm facing a problem here where I work, there is a project when initialized works with 1 SQL Server Instance, 2 DB2 instances.
The problem is, this project was based on another project to keep the similar structure, but on this new project we don't use the SQL Server instance who is in reference on some xml files, I tried to comment these references, when I start the project on Tomcat, the project show me few errors.
As a new on Spring, how can I remove this connection properly??
beans.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:jaxws="http://cxf.apache.org/jaxws"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd">
<jee:jndi-lookup id="IP_ICMS_RJ" jndi-name="java:comp/env/IP_ICMS_RJ" />
<jee:jndi-lookup id="USUARIO_ICMS_RJ" jndi-name="java:comp/env/USUARIO_ICMS_RJ" />
<jee:jndi-lookup id="SENHA_ICMS_RJ" jndi-name="java:comp/env/SENHA_ICMS_RJ" />
<jee:jndi-lookup id="IP_ICMS_SP" jndi-name="java:comp/env/IP_ICMS_SP" />
<jee:jndi-lookup id="USUARIO_ICMS_SP" jndi-name="java:comp/env/USUARIO_ICMS_SP" />
<jee:jndi-lookup id="SENHA_ICMS_SP" jndi-name="java:comp/env/SENHA_ICMS_SP" />
<jee:jndi-lookup id="PSACWSDocumentURL" jndi-name="java:comp/env/PSACWSDocumentURL" />
<jee:jndi-lookup id="PSACWSEndPoint" jndi-name="java:comp/env/PSACWSEndPoint" />
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
<aop:aspectj-autoproxy/>
<bean id="FaleConoscoWSBean" class="br.com.embratel.faleconosco.ws.FaleConoscoWSBean">
</bean>
<bean id="RoboFaleConoscoWSBean" class="br.com.embratel.faleconosco.ws.RoboFaleConoscoWSBean">
</bean>
<!-- <bean id="faleConoscoDS" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/FaleConoscoDS" />
</bean> -->
<bean id="icmsRJDS" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/ICMS_RJ_DS" />
</bean>
<bean id="icmsSPDS" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/ICMS_SP_DS" />
</bean>
<bean id="icmsRJ" class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
<constructor-arg ref="icmsRJDS" />
</bean>
<bean id="icmsSP" class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
<constructor-arg ref="icmsSPDS" />
</bean>
<util:map id="icmsPropertiesMap">
<entry key="IP_RJ" value-ref="IP_ICMS_RJ" />
<entry key="USUARIO_RJ" value-ref="USUARIO_ICMS_RJ" />
<entry key="SENHA_RJ" value-ref="SENHA_ICMS_RJ" />
<entry key="IP_SP" value-ref="IP_ICMS_SP" />
<entry key="USUARIO_SP" value-ref="USUARIO_ICMS_SP" />
<entry key="SENHA_SP" value-ref="SENHA_ICMS_SP" />
</util:map>
<!-- Lista de processadores de OS -->
<util:list id="processors">
<bean class="br.com.embratel.faleconosco.ws.service.os.processor.ClienteProcessor" />
<bean class="br.com.embratel.faleconosco.ws.service.os.processor.ServicoEquipamentoProcessor" />
<bean class="br.com.embratel.faleconosco.ws.service.os.processor.SuspensaoProcessor" />
<bean class="br.com.embratel.faleconosco.ws.service.os.processor.SaldoProcessor" />
<bean class="br.com.embratel.faleconosco.ws.service.os.processor.DebitoAutomaticoProcessor" />
</util:list>
<context:annotation-config />
<context:component-scan base-package="br.com.embratel.faleconosco">
<context:include-filter type="annotation" expression="javax.jws.WebService" />
</context:component-scan>
<!-- <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="faleConoscoDS" />
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="SQL_SERVER" />
<property name="databasePlatform" value="org.hibernate.dialect.SQLServerDialect" />
<property name="showSql" value="true" />
<property name="generateDdl" value="false" />
</bean>
</property>
<property name="jpaPropertyMap">
<map>
<entry key="org.hibernate.type" value="true" />
<entry key="org.hibernate.transaction" value="true" />
</map>
</property>
</bean>
<bean id="jpaTemplate" class="br.com.embratel.faleconosco.ws.dao.JpaTemplateExt">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
enable the configuration of transactional behavior based on annotations
<tx:annotation-driven transaction-manager="transactionManager" /> -->
<bean id="ProtocoloWS" class="org.springframework.remoting.jaxrpc.JaxRpcPortProxyFactoryBean" scope="prototype">
<property name="serviceFactoryClass">
<value>org.apache.axis.client.ServiceFactory</value>
</property>
<property name="wsdlDocumentUrl" ref="PSACWSDocumentURL" />
<property name="endpointAddress" ref="PSACWSEndPoint" />
<property name="serviceName">
<value>ProtocoloWSService</value>
</property>
<property name="namespaceUri">
<value>http://webservices.protocolounico.embratel.com.br/</value>
</property>
<property name="portName">
<value>ProtocoloWSPort</value>
</property>
<property name="portInterface">
<value>br.com.embratel.protocolounico.webservices.ProtocoloWS</value>
</property>
<property name="serviceInterface">
<value>br.com.embratel.protocolounico.webservices.ProtocoloWS</value>
</property>
<property name="customPropertyMap">
<map>
<entry>
<key><value type="java.lang.String">axis.connection.timeout</value></key>
<value type="java.lang.Integer">300000</value>
</entry>
</map>
</property>
</bean>
<bean id="LoggerAspect" class="br.com.embratel.faleconosco.ws.aop.LoggerAspect">
</bean>
<jaxws:endpoint xmlns:tns="http://ws.faleconosco.embratel.com.br/" id="faleconoscowsbean"
implementor="#FaleConoscoWSBean" wsdlLocation="wsdl/faleconoscowsbean.wsdl" endpointName="tns:FaleConoscoWSPort"
serviceName="tns:FaleConoscoWSService" address="/FaleConoscoWSPort">
<jaxws:features>
bean class="org.apache.cxf.feature.LoggingFeature" /
</jaxws:features>
</jaxws:endpoint>
<jaxws:endpoint xmlns:tns="http://ws.faleconosco.embratel.com.br/" id="robofaleconoscowsbean"
implementor="#RoboFaleConoscoWSBean" wsdlLocation="wsdl/robofaleconoscowsbean.wsdl"
endpointName="tns:RoboFaleConoscoWSPort" serviceName="tns:RoboFaleConoscoWSService" address="/RoboFaleConoscoWSPort">
<jaxws:features>
bean class="org.apache.cxf.feature.LoggingFeature" /
</jaxws:features>
</jaxws:endpoint>
</beans>
ERRORS
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'FaleConoscoWSBean': Autowiring of fields failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private br.com.embratel.faleconosco.ws.service.usuario.UsuarioService br.com.embratel.faleconosco.ws.FaleConoscoWSBean.usuarioService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'usuarioServiceImpl': Autowiring of fields failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private br.com.embratel.faleconosco.ws.service.email.EnviarEmailService br.com.embratel.faleconosco.ws.service.usuario.UsuarioServiceImpl.enviarEmailService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'enviarEmailServiceImpl': Autowiring of fields failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private br.com.embratel.faleconosco.ws.dao.JpaTemplateExt br.com.embratel.faleconosco.ws.service.BaseServiceImpl.jpaTemplate; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [br.com.embratel.faleconosco.ws.dao.JpaTemplateExt] is defined: Unsatisfied dependency of type [class br.com.embratel.faleconosco.ws.dao.JpaTemplateExt]: expected at least 1 matching bean
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessAfterInstantiation(AutowiredAnnotationBeanPostProcessor.java:243)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:959)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:472)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
at java.security.AccessController.doPrivileged(Native Method)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:429)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:728)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:380)
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:255)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45)
at
Well I Studied better Spring and re create the xml.
I removed this part of the code from the code above.
Creating the file from the begining.
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="SQL_SERVER" />
<property name="databasePlatform" value="org.hibernate.dialect.SQLServerDialect" />
<property name="showSql" value="true" />
<property name="generateDdl" value="false" />
</bean>
</property>

Setting FlushMode.COMMIT in Spring

I would like set my Hibernate/JPA FlushMode to COMMIT, but in configuration file (applicationContenxt.xml is one of my files), i have a entityManager in my DAO, but i don't know how to set this in configuration file.
So, this is my applicationContext.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"
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">
<!-- Seta anotaƧoes para serem usadas pelo Spring -->
<context:annotation-config />
<!-- Define o pacote onde o Spring vai procurar por beans anotados -->
<context:component-scan
base-package="br.com.sender" />
<!-- define que as transaƧoes irao ser anotadas -->
<tx:annotation-driven proxy-target-class="true" />
<!-- Configuracao do Banco de Dados -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost/sender" />
<property name="username" value="postgres" />
<property name="password" value="pgadmin" />
</bean>
<!-- Configuracao do Hibernate -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="senderPU" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="org.hibernate.dialect.PostgreSQLDialect" />
<property name="showSql" value="true" />
</bean>
</property>
</bean>
<!-- Configuracao do gerente de transacoes do Spring -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
</beans>
EDIT 1:
I tried the following in applicationContext.xml
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect">
<property name="flushMode" value="COMMIT"/>
</bean>
</property>
Tomcat error:
aused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'flushMode' of bean class [org.springframework.orm.jpa.vendor.HibernateJpaDialect]: Bean property 'flushMode' 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.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:1052)
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:921)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:76)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:58)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1358)
... 53 more
SOLUTION:
After a lot of research, i found a solution. I setted the FlushMode in #PersistenceContext in my BasicDAO class. Look:
#PersistenceContext(type = javax.persistence.PersistenceContextType.EXTENDED,
properties = #PersistenceProperty(name="org.hibernate.flushMode", value="COMMIT"))
protected EntityManager entityManager;
This works fine. I removed all #Transactional annotation from my "find" functions, because with #Transactional the "COMMIT" are fired and flush too.

EntityManager and persist method not working properly

I'm in trouble here..
I'm new using Spring + Hibernate in a Java SE application...
I'm trying to instantiate the entityManager, but it's not working
I'm using the annotation #PersistenceUnit, like this:
#PersistenceUnit
public void setEmf(EntityManager emf) {
this.emf = emf;
}
And it works "fine", but it doesn't persist =/
When I change to
#PersistenceContext
public void setEmf(EntityManager emf) {
this.emf = emf;
}
It came out the following error:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'daoAbstract' defined in class path resource [applicationContext.xml]: Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type '$Proxy10 implementing org.hibernate.ejb.HibernateEntityManagerFactory,org.springframework.orm.jpa.EntityManagerFactoryInfo' to required type 'javax.persistence.EntityManager' for property 'emf'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [$Proxy10 implementing org.hibernate.ejb.HibernateEntityManagerFactory,org.springframework.orm.jpa.EntityManagerFactoryInfo] to required type [javax.persistence.EntityManager] for property 'emf': no matching editors or conversion strategy found
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:532)
Here's my applicationContext.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: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-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<bean id="ConfiguradorDePropriedades"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<description>The service properties file</description>
<property name="location" value="file:AppConfig.properties" />
</bean>
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<!-- <property name="persistenceUnitName" value="ChatJpa" /> -->
<property name="persistenceXmlLocation" value="classpath:persistence.xml" />
<property name="dataSource" ref="dataSourceLocal" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="${database}" />
<property name="showSql" value="false" />
<property name="generateDdl" value="true" />
</bean>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="dataSourceLocal"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.user}" />
<property name="password" value="${jdbc.pass}" />
</bean>
<bean id="daoAbstract" class="com.planner.pvc.dao.DaoAbstract">
<property name="emf" ref="entityManagerFactory" />
</bean>
<bean id="clienteDao" class="com.planner.pvc.dao.ClienteDaoImpl">
</bean>
<bean id="pvcMainController" class="com.planner.pvc.controller.PVCMainController">
<property name="dao" ref="clienteDao" />
</bean>
</beans>
And persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="ChatJpa">
<properties>
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.connection.driver_class" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<!-- <property name="hibernate.cache.provider_class" value="net.sf.ehcache.hibernate.EhCacheProvider" />
<property name="hibernate.cache.use_query_cache" value="true" />
<property name="hibernate.hbm2ddl.auto" value="update" /> -->
</properties>
</persistence-unit>
</persistence>
Any help would be appreciated.
Thanks
This line is the problem:
<bean id="daoAbstract" class="com.planner.pvc.dao.DaoAbstract">
<property name="emf" ref="entityManagerFactory" />
</bean>
Instead of doing this, let Spring inject the emf field annotated with #PersistenceContext, this will happen if you have a <context:component-scan.../> or <context:annotation-config/> tags in your application context or just add the latter.

spring - how to autowire data source?

I'm having some problem with autowire and DI in general, so I hope that someone can help cause I've been stuck for days now.
This is the code:
#Service
public class TicketsController implements Controller {
private TicketManager ticketManager;
#Autowired
public void setTicketManager(TicketManager ticketManager) {
this.ticketManager = ticketManager;
}
...
}
#Service
public class SimpleTicketManager implements TicketManager {
private TicketsDao ticketsDao;
#Autowired
public void setTicketsDao(TicketsDao ticketsDao) {
this.ticketsDao = ticketsDao;
}
...
}
#Repository
public class JdbcTicketDao implements TicketsDao {
private DataSource dataSource;
#Autowired
public void setDataSource(DataSource dataSource) {
this.dataSource=dataSource;
this.jdbcTemplate = new JdbcTemplate(this.dataSource);
}
...
}
public final class AppContext {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
BeanFactory factory = context;
TicketsController ticketsController = (TicketsController) factory.getBean("ticketsController");
}
...
}
In my beans.xml I've got:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mytckdb"/>
<property name="username" value="user"/>
<property name="password" value="pass"/>
</bean>
<context:component-scan base-package="bp.dao" />
<context:component-scan base-package="bp.mvc" />
<context:component-scan base-package="bp.svc" />
<context:component-scan base-package="bp.view" />
This doesn't work and I get:
Error creating bean with name 'jdbcTicketDao': Injection of autowired dependencies failed
... nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No matching bean of type [javax.sql.DataSource] found for dependency.`
Can someone please help out with this? What am I doing wrong? It seems that autowiring is working all until the next step where it fails when injecting dataSource.
EDIT: I was playing with the code, and forgot #Autowire before setDataSource() but it is supposed to be there.
Maybe you're missing wiring configuration, try
<context:annotation-config/>
This will be due to the order of bean instance creation. Your DAO has been instantiated before the dataSource instance created.
Keep your data Source bean definition before
other way is , define your dataSource definitions in a separate xml and import that before
Try org.apache.commons.dbcp.BasicDataSource :
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="com.mysql.jdbc.Driver"
p:url="jdbc:mysql://127.0.0.1:3306/mytckdb?autoReconnect=true"
p:username="user" p:password="pass" />
I use JPA so generally prefer to create EntityManagerFactory and use that
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="PU" />
<property name="jpaVendorAdapter">
<bean id="jpaAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="${database}" />
<property name="showSql" value="true" />
<property name="generateDdl" value="false" />
</bean>
</property>
</bean>
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
Looks like you are using Spring 2.0 but i think context:component-scan was introduced in Spring 2.5.
Maybe update spring xml-config and spring dependencies to 2.5?
Change
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mytckdb"/>
<property name="username" value="user"/>
<property name="password" value="pass"/>
</bean>
to
<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/mytckdb"/>
<property name="username" value="user"/>
<property name="password" value="pass"/>
</bean>
The property is called driverClassName, not driverClass.
Also, you don't need multiple context:component-scan elements You can change
<context:component-scan base-package="bp.dao" />
<context:component-scan base-package="bp.mvc" />
<context:component-scan base-package="bp.svc" />
<context:component-scan base-package="bp.view" />
To
<context:component-scan base-package="bp.dao,bp.mvc,bp.svc,bp.view" />

Categories