Transaction with Spring and Mybatis - java

I have this mapper-config.xml.There is the DAO and the BLM fot the Game class:
<bean id="DAOGame" class="it.certimeter.nagima.dao.game.DAOGame">
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
<bean id="BLMGameTarget" class="it.certimeter.nagima.blm.game.BLMGame">
<property name="daoGame" ref="DAOGame" />
</bean>
And the bean for the transaction:
<bean class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" id="BLMGame">
<property name="proxyInterfaces">
<list>
<value>it.certimeter.nagima.blm.game.IBLMGame</value>
</list>
</property>
<property name="transactionManager">
<ref bean="transactionManager"/>
</property>
<property name="target">
<ref bean="BLMGameTarget"/>
</property>
<property name="transactionAttributes">
<props>
<prop key="saveGame">PROPAGATION_REQUIRED, -it.fondsai.jeffs.core.exception.service.appl.JeffsServiceApplException</prop>
</props>
</property>
<!-- <property name="anonymousAccess" value="true"/> -->
</bean>
But I have this error:
nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [it.certimeter.nagima.blm.game.IBLMGame] is defined: expected single matching bean but found 2: BLMGameTarget,BLMGame
Where am I wrong??

Yeah, the issue with what Ben commented on. I just ran into this myself the other day.
This issue brings a bad code smell with it, but if you want a workaround, I would suggest the following:
Go to where you #Autowire your IBLMGame instance. In addition to the #Autowire annotation, you can provide a #Qualifier annotation and give a String value that represents the bean name you actually want wired in.
So for your case, it could look something like this:
#Autowired
#Qualifier("BLMGameTarget") // you can substitute in "BLMGame" if that's the bean you want
IBLMGame iblmGame;

Related

Spring 3 and hibernate 4.X facing a transaction Manager Exception in destroy-method

We are currently using Spring 3 with hibernate 4.4 in our project.
A snippet of my database config xml looks as follows
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass">
<value>${jdbc.driver.className}</value>
</property>
<property name="jdbcUrl">
<value>${jdbc.url}</value>
</property>
<property name="user">
<value>${jdbc.username}</value>
</property>
<property name="password">
<value>${jdbc.password}</value>
</property>
</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">${jdbc.hibernate.dialect}</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.jdbc.batch_size">20</prop>
<prop key="hibernate.current_session_context_class">managed</prop>
</props>
</property>
<property name="packagesToScan" value="com.sample.entity" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<tx:annotation-driven />
While we were testing our war , we came across this exception .
13:27:19,511 ERROR TransactionInterceptor:419 - Application exception overridden by rollback exception
org.springframework.beans.factory.BeanCreationNotAllowedException:
Error creating bean with name 'transactionManager': Singleton bean creation not allowed
while the singletons of this factory are in destruction (Do not request a bean from a
BeanFactory in a destroy method implementation!)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:212)
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.transaction.interceptor.TransactionAspectSupport.determineTransactionManager(TransactionAspectSupport.java:248)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:100)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
I am unable to figure out if this is because of the destroy-method =close mentioned in the config file . I am also using the #Transactional annotation at both the Service layer and the database layer . Will this cause any issue?
We were trying to test a scenario where in multiple people (around 150) are all trying to access our application at the same time.
Kindly help me out.. Please do let me know, If more details are needed.
Thanks
As the spring doc says in Section 3.6.1.5
The order of startup and shutdown invocations can be important. If a "depends-on" relationship exists between any two objects, the dependent side will start after its dependency, and it will stop before its dependency. However, at times the direct dependencies are unknown. You may only know that objects of a certain type should start prior to objects of another type. In those cases, the SmartLifecycle interface defines another option, namely the getPhase() method as defined on its super-interface, Phased.
So you need the bean to implement the SmartLifeCycle, Javadoc for SmartLifeCycle Interface 1: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-lifecycle-processor.
Hope this helps !!

Concatenate string in spring xml configuration

I need to concatenate the string value of a spring bean, to an existing string, and then set it as an attribute of another bean:
<bean id="inet" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetClass"><value>java.net.InetAddress</value></property>
<property name="targetMethod"><value>getLocalHost</value></property>
</bean>
<bean id="host" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject"><ref local="inet"/></property>
<property name="targetMethod"><value>getHostName</value></property>
</bean>
At this point, I have the hostname, in the 'host' bean. I now need to concatenate it and pass it to the publishedEndpointUrl attribute. Something like this:
<jaxws:endpoint
id="foo"
publishedEndpointUrl= "http://" + host + "/Foo"
implementor="com.example.v1.foo"
address="/v1/Foo"/>
How is this done using spring xml configuration?
You could use Spring-EL and factory-method:
<bean id="localhost" class="java.net.InetAddress" factory-method="getLocalHost" />
<bean id="publishedUrl" class="java.lang.String">
<constructor-arg value="#{'http://' + localhost.hostName + '/Foo'}" />
</bean>
<jaxws:endpoint
...
publishedEndpointUrl="#publishedUrl"
...
EDIT:
The jaxws:endpoint tag appears to be able to reference bean values by using the #beanId notation but does not like Spring-EL. So by constructing a String bean, we get around this and it still looks fairly neat.
You need to look at PropertyPlaceholderConfigurer. This allows you define global properties, which can either come from a properties file, or in your case, you can define a default value, in which case it's just a global property. The following will work:
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName">
<value>SYSTEM_PROPERTIES_MODE_OVERRIDE</value>
</property>
<property name="properties">
<props>
<prop key="driver">jdbc.oracle.Driver</prop>
<prop key="dbname">fred</prop>
</props>
</property>
<property name="locations">
<list>
<value>file:properties/application.properties</value>
</list>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"><value>${driver}</value></property>
<property name="url"><value>jdbc:${dbname}</value></property>
</bean>
This means that you have default values for ${driver} and ${dbname}, which are used to define the data source. These values can be overridden in the application.properties file, or even as a -D option on the command line.
As jaxws:* namespace does not like Spring EL, an alternative could be to declare an EndpointImpl bean, instead of the jaxws:endpoint object.
It is some more work, but as pointed out in http://cxf.apache.org/docs/jax-ws-configuration.html, it is the actual implementation used by the namespace declaration.
You can mix propertyplaceholder vars and Spring EL:
<bean id="dataSource" class="xx.xxx.xxxxx.datasource.DataSourceWrapper" destroy-method="close">
<property name="dataSourceClassName" value="${db.dataSourceClassName}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />
<property name="maximumPoolSize" value="${db.maxConnections}" />
<property name="connectionTimeout" value="${db.connectionTimeout}" />
<property name="dataSourceProperties">
<props>
<prop key="databaseName">${db.databaseName}</prop>
<prop key="serverName">${db.serverName}#{':'}${db.port}</prop>
</props>
</property>
Look at ${db.serverName}#{':'}${db.port} concat.

Hibernate + Spring - xml mapping not found

I have simple application with following folder structure:
ProjFolder
|-----src
|----------packagename
|---------------{sourcefiles}
|----------META-INF
|---------------{beans.xml}
|---------------{hibernate.cfg.xml}
|---------------{EntityMapping.hbm.xml}
here is the part of beans.xml Spring config file:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:./META-INF/jdbc.properties" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:./META-INF/hibernate.cfg.xml" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>classpath:./META-INF/EntityMapping.hbm.xml</value>
</list>
</property>
</bean>
<tx:annotation-driven transaction-manager="txManager" />
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
when i start my unit tests i getting following exception:
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'wrapperClass' defined in class path resource
[META-INF/beans.xml]: Cannot resolve reference to bean 'wrapperClassField'
while setting constructor argument; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'xmlBooksource' defined in class path resource
[META-INF/beans.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 [META-INF/beans.xml]: Invocation of init method failed;
nested exception is java.io.FileNotFoundException: class path resource
[classpath:/META-INF/EntityMapping.hbm.xml] cannot be opened because it does not exist
The same exception is thrown when i type
<property name="mappingResources">
<list>
<value>EntityMapping.hbm.xml</value>
</list>
</property>
Why spring cant find this file and how i must fill its location to make this code work?
Thanks in advance.
Have you tried removing the classpath: prefix? In looking at the Hibernate code, the mappingResources setter expects passes the strings to new ClassPathResource(String). This expects classpath resources already. The string then gets passed to ClassLoader.getResourceAsStream(String). None of this code would strip the "classpath:" prefix from the front of the resource string.
I'm not sure the error message is consistent with the beans.xml content you posted.
In the error you have
[classpath:/META-INF/EntityMapping.hbm.xml]
which isn't the same as
classpath:./META-INF/EntityMapping.hbm.xml
Notice the missing "." at the beginning in the error.
The second beans.xml configuration, should probably produce a different error message with:
[classpath:EntityMapping.hbm.xml]
This would be searching for the file in the root of your compiled application (jar, war, exploded, what have you).
I have successfully configure Hibernate 4 with Spring 3.1. My applicationContext.xml file is inside web-inf folder and has the following hibernate cofiguration:
<!-- Session Factory Declaration -->
<bean id="SessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="DataSource" />
<!--
<property name="annotatedClasses">
<list>
<value>iltaf.models.Levels</value>
</list>
</property>
-->
<property name="mappingLocations" value="classpath:iltaf/models/*.hbm.xml" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- Enable the configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="txManager"/>
<!-- Transaction Manager is defined -->
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="SessionFactory"/>
</bean>
</beans>
and I have separate hibernate.cfg.xml file inside my src folder. I am using Eclipse Juno Java EE version.

No unique bean of type [javax.persistence.EntityManager] is defined

I am using JUnit 4 to test Dao Access with Spring (annotations) and JPA (hibernate). The datasource is configured through JNDI(Weblogic) with an ORacle(Backend). This persistence is configured with just the name and a RESOURCE_LOCAL transaction-type
The application context file contains notations for annotations, JPA config, transactions, and default package and configuration for annotation detection.
I am using Junit4 like so:
ApplicationContext
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="workRequest"/>
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="${database.target}"/>
<property name="showSql" value="${database.showSql}" />
<property name="generateDdl" value="${database.generateDdl}" />
</bean>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>workRequest</value>
</property>
<property name="jndiEnvironment">
<props>
<prop key="java.naming.factory.initial">weblogic.jndi.WLInitialContextFactory</prop>
<prop key="java.naming.provider.url">t3://localhost:7001</prop>
</props>
</property>
</bean>
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
JUnit TestCase
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "classpath:applicationContext.xml" })
public class AssignmentDaoTest {
private AssignmentDao assignmentDao;
#Test
public void readAll() {
assertNotNull("assignmentDao cannot be null", assignmentDao);
List<Assignment> assignments = assignmentDao.findAll();
assertNotNull("There are no assignments yet", assignments);
}
}
regardless of what changes I make I get:
No unique bean of type [javax.persistence.EntityManager] is defined
Any hint on what this could be. I am running the tests inside eclipse.
Your Spring context has a bean definition using LocalContainerEntityManagerFactoryBean. This creates an EntityManagerFactory, not an EntityManager.
AssignmentDao needs to get itself wired with an EntityManagerFactory.
Alternatively, you can replace the LocalContainerEntityManagerFactoryBean with a LocalEntityManagerFactoryBean, which will create an EntityManager directly. However, you need to be careful with that one, it has some downsides. See that part of the Spring docs for a full explanation of the options.
It's confusing, because the naming conventions of JPA and Spring overlap each other, so naming these classes is a real bugger.

Spring: Getting FactoryBean object instead of FactoryBean.getObject()

Short question: If I have class that impelemnts FactoryBean interface, how can I get from FactoryBean object itself instead of FactoryBean.getObject()?
Long question: I have to use 3-rd party Spring based library which is hardly use FactoryBean interface. Right now I always must configure 2 beans:
<!-- Case 1-->
<bean id="XYZ" class="FactoryBean1" scope="prototype">
<property name="steps">
<bean class="FactoryBean2">
<property name="itemReader" ref="aName"/>
</bean>
</property>
</bean>
<bean id="aName" class="com.package.ClassName1" scope="prototype">
<property name="objectContext">
<bean class="com.package.ABC"/>
</property>
</bean>
<!-- Case 2-->
<bean id="XYZ2" class="FactoryBean1" scope="prototype">
<property name="steps">
<bean class="FactoryBean2">
<property name="itemReader" ref="aName2"/>
</bean>
</property>
</bean>
<bean id="aName2" class="com.package.ClassName1" scope="prototype">
<property name="objectContext">
<bean class="com.package.QWE"/>
</property>
</bean>
Actyually defintion of a bean with name "XYZ" (compare with "XYZ2") never will be changed, but because of factory nature I must copy the code for each configuration.
Definition of a bean with name "aName" always will be new (i.e. each configuration will have own objectContext value).
I would like to simplify the configuration have a single factory bean (remove "XYZ2" and rid of link to "aName"):
<bean id="XYZ" class="FactoryBean1" scope="prototype">
<property name="steps">
<bean class="FactoryBean2"/>
</property>
</bean>
<bean id="aName" class="com.package.ClassName1" scope="prototype">
<property name="objectContext">
<bean class="com.package.ABC"/>
</property>
</bean>
<bean id="aName2" class="com.package.ClassName1" scope="prototype">
<property name="objectContext">
<bean class="com.package.QWE"/>
</property>
</bean>
Unfortunately, it's not as simple as I expect. I suppose to glue factory (i.e. XYZ bean from the example) with necessary objects (i.e. "aName", "aName2") at runtime.
The approach doesn't work because when I ask Spring for FactoryBean object it returns to me FactoryBean.getObject() which impossible to instanciate at that time because of missing itemReader value.
I hope that SpringSource foresee my case I can somehome "hook" FactoryBean.getObject() call to provide all necessary properties at runtime.
Another complexity that disturb me a bit it's chains of Factories (Factory1 get an object from Factory2 that I have to "hook" at runtime).
Any ideas will be appreciated.
It's the & (ampersand), not the At-symbol, see Spring Framework documentation: Customizing instantiation logic using FactoryBeans
<property name="factoryBean" ref="&theFactoryBean" />
You can get the factory bean itself using the & syntax in the spring config:
<property name="factoryBean" ref="&theFactoryBean" />
as opposed to:
<property name="createdBean" ref="theFactoryBean" />

Categories