Not active transaciotn: javax.persistence.TransactionRequiredException: Executing an update/delete query - java

why is my transaction not active?
I have this message:
"javax.persistence.TransactionRequiredException: Executing an update/delete query"
I can't find why
aplicationContext:
<?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:c="http://www.springframework.org/schema/c"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
<context:annotation-config />
<context:component-scan base-package="com.model.dao" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/punit" />
<property name="username" value="root" />
<property name="password" value="" />
<property name="maxActive" value="10" />
<property name="maxIdle" value="10" />
</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="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
</bean>
</property>
<property name="jpaPropertyMap">
<map>
<entry key="hibernate.connection.useUnicode" value="true" />
<entry key="hibernate.connection.characterEncoding" value="UTF-8" />
<entry key="hibernate.jdbc.batch_size" value="30" />
</map>
</property>
</bean>
<!-- Transaction Manager -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<!-- <property name="dataSource" ref="dataSource" /> -->
</bean>
DAO Impl
#Component
public class UserDaoImpl implements UserDao {
#PersistenceContext(unitName="punit")
private EntityManager em;
protected UserDaoImpl() {
}
//other ovverrides like find, get
#Override
#Transactional
public void deleteUser(String mail, String password) {
Query q = em.createQuery("DELETE FROM User u WHERE u.mail='"
+ mail + "'AND u.password='" + password
+ "'");
try{
q.executeUpdate();
this.em.flush();
}catch (PersistenceException pe){
pe.printStackTrace();
}
}
}
persistence.xml
<?xml version="1.0"?>
<persistence 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_2_0.xsd"
version="2.0">
<persistence-unit transaction-type="RESOURCE_LOCAL" name="punit">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<!-- e.g. validate | update | create | create-drop -->
</properties>
</persistence-unit>
</persistence>
RemoveUser
public class RemoveUser extends BaseAction{
private static final long serialVersionUID = 1L;
private String mail;
private String password;
User user;
#Autowired
UserDaoImpl u;
#Action(value = "removeUser", results = {
#Result(name="success", location = "pages/loginform.jsp"),
#Result(name="login", location = "pages/loginform.jsp")})
public String removeUser(){
u.deleteUser(mail, password);
//..logoutAction
return SUCCESS;
}
//..getters and setters...
}
Error
javax.persistence.TransactionRequiredException: Executing an update/delete query
at org.hibernate.ejb.AbstractQueryImpl.executeUpdate(AbstractQueryImpl.java:96)
at com.model.dao.UserDaoImpl.deleteUser(UserDaoImpl.java:73)
at com.actions.RemoveUser.removeUser(RemoveUser.java:31)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:450)
at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:289)

I don't see a <tx:annotation-driven transaction-manager="transactionManager"/> in your xml configuration.

Another possible cause of this error. Make certain to use the correct annotation.
In Spring, use.
org.springframework.transaction.annotation.Transactional
not
javax.transaction.Transactional.
This has bit me numerous times in unit tests.

Related

How to map specific columns in spring data jpa?

Whenever I on click submit button with some value, I want to select some columns from database and show it on my jsp page. The form is successfully submitted but I'm getting this error:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.psc.Entity.CandidateappearagainstadvtcodeEntity
So I think whatever data the repository is returning is not mapped with Entity. Please suggest, how to resolve this issue?
Controller:
#RequestMapping(value = "/getCandidateDetails", method = RequestMethod.POST)
public String getCandidateDetails(Model model,#RequestParam("studentmasterid") String studentmasterid){
System.out.println(studentmasterid);
List<CandidateappearagainstadvtcodeEntity> candidates=candidateappearagainstadvtcodeEntityRepository.findBystudentmasterid(studentmasterid);
return "payments";
}
Model looks like this:
#Entity
#Table(name = "CANDIDATEAPPEARAGAINSTADVTCODE", schema = "PSCNEPALCOMMERCIALDATABASEU1", catalog = "")
public class CandidateappearagainstadvtcodeEntity {
private long id;
private String advertisementcode;
private Integer ageonlastdateday;
private Integer ageonlastdatemonth;
private Integer ageonlastdateyear;
private String applicationnumber;
private String attendancestatus;
private String candidatefirstname;
private String dateofbirthinnepali;
private String documentverificationstatus;
private String examinationcenterid;
private String examresultsstatus;
private String fathername;
private Long firstcoding;
private String studentmasterid;
//getters setters//
Repository:
public interface CandidateappearagainstadvtcodeEntityRepository extends JpaRepository<CandidateappearagainstadvtcodeEntity,Long> {
#Query("select c.studentmasterid,c.advertisementcode,c.candidatefirstname from CandidateappearagainstadvtcodeEntity c where c.studentmasterid=?1")
List<CandidateappearagainstadvtcodeEntity> findBystudentmasterid(String masterId);
}
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:util="http://www.springframework.org/schema/util"
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-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.psc"/>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>/WEB-INF/db.properties</value>
</property>
</bean>
<!-- BoneCP configuration -->
<bean id="mainDataSource" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close">
<property name="driverClass" value="${jdbc.driver}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="idleConnectionTestPeriodInMinutes" value="60"/>
<property name="idleMaxAgeInMinutes" value="240"/>
<property name="maxConnectionsPerPartition" value="30"/>
<property name="minConnectionsPerPartition" value="10"/>
<property name="partitionCount" value="3"/>
<property name="acquireIncrement" value="5"/>
<property name="statementsCacheSize" value="100"/>
<property name="releaseHelperThreads" value="3"/>
</bean>
<!-- SPRING - JPA -->
<jpa:repositories
base-package="com.psc" />
<bean class="org.springframework.orm.jpa.JpaTransactionManager"
id="transactionManager">
<property name="entityManagerFactory"
ref="entityManagerFactory" />
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
</property>
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="mainDataSource" />
<property name="packagesToScan" value="com.psc"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="true" />
<property name="showSql" value="false"/>
<property name="databasePlatform" value="org.hibernate.dialect.Oracle12cDialect"/>
<property name="database" value="ORACLE"/>
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle12cDialect</prop>
</props>
</property>
</bean>
</beans>
A JPA repository usually returns the domain model. From the docs
Spring Data Repositories usually return the domain model when using query methods. However, sometimes, you may need to alter the view of that model for various reasons. In this section, you will learn how to define projections to serve up simplified and reduced views of resources.
Your repository method findBystudentmasterid will be returning a list Object[] hence the ClassCastException.If you want to get specific columns try Projections.
Chekout the docs and this answer on how to use projections.

Spring JPA error: A JTA EntityManager cannot use getTransaction()

I've got a problem with my Spring web application with JPA and Glassfish server. When I'm trying to add new entry to a database (entityManager.persist()), I receive:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is java.lang.IllegalStateException: A JTA EntityManager cannot use getTransaction()
Here's my code:
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="LibraryPU">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/sample</jta-data-source>
<properties>
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.SunOneJtaPlatform"/>
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
dispatcher-servlet.xml
<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?xml version="1.0" encoding="UTF-8"?> -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
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-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<context:component-scan base-package="service, controller, dao" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" />
<property name="persistenceUnitName" value="LibraryPU" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<property name="jpaDialect" ref="jpaDialect" />
</bean>
<bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="HSQL" />
<property name="databasePlatform" value="org.hibernate.dialect.HSQLDialect" />
</bean>
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.apache.derby.jdbc.ClientDriver" />
<property name="url" value="jdbc:derby://localhost:1527/Library" />
<property name="username" value="app" />
<property name="password" value="app" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
UserDao.java
package dao;
import entity.User;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
#Repository("userDao")
#Transactional
public class UserDao {
#PersistenceContext
private EntityManager entityManager;
#Transactional
public void insert(User user) {
entityManager.persist(user);
entityManager.flush();
}
}
Thanks in advance!
if You want to use JTA transaction in your code then
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
remove the JpaTransactionManager and replace it with a JTA transaction manager.
Also define the transacation-type="JTA" like
<persistence-unit name="LibraryPU" transaction-type="JTA">
in persistence.xml.

Insert into two tables in two different database

My Java web application on spring framework is using two database say database-1 and database-2. Both database have User table. What I am trying to do is to insert record into both tables at same time.
There are two persistence-unit in the persistence.xml that is pointing out to database.
Here is my persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence 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"
version="1.0">
<persistence-unit name="p1-jpa" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:jboss/datasources/MySqlDS2</jta-data-source>
<class>com.xyz.entity.User</class>
<exclude-unlisted-classes />
<properties>
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.HashtableCacheProvider" />
</properties>
</persistence-unit>
<persistence-unit name="p2-jpa" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:jboss/datasources/MySqlDS2</jta-data-source>
<class>com.mmxhealthcare.entity.MMASCUser</class>
<exclude-unlisted-classes />
<properties>
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.HashtableCacheProvider" />
</properties>
</persistence-unit>
</persistence>
Now Whenever I am trying to add user, it is inserted only in Database-1. I am not getting any exception.
Here is my spring-servlet.xml file:-
<?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:jaxrs="http://cxf.apache.org/jaxrs"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util" xmlns:security="http://www.springframework.org/schema/security"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
<property name="order" value="0"/>
</bean>
<!-- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean> -->
<context:property-placeholder location="classpath:config.properties" />
<context:annotation-config />
<context:component-scan base-package="com.xyz.controller" />
<context:component-scan base-package="com.xyz.service" />
<context:component-scan base-package="com.xyz.dao" />
<context:component-scan base-package="com.xyz.security" />
<context:component-scan base-package="com.xyz.dto" />
<context:component-scan base-package="com.xyz.util" />
<context:component-scan base-package="com.xyz.entity" />
<tx:annotation-driven />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="transactionManager1" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="aaentityManagerFactory" />
</bean>
<bean id="transactionManager2" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="mmascentityManagerFactory" />
</bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="d1SourceLocal" />
<property name="persistenceUnitName" value="p1-jpa" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
</bean>
<bean id="mmascentityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="d2DataSourceLocal" />
<property name="persistenceUnitName" value="p2-jpa" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
</bean>
<!-- <bean id="dataSourceLocal" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:jboss/datasources/MySqlDS2"/>
</bean> -->
<!-- Local -->
<bean id="d1SourceLocal"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.username}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="d2DataSourceLocal"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${d2-database.driver}" />
<property name="url" value="${d2-database.url}" />
<property name="username" value="${d2-database.username}" />
<property name="password" value="${d2-database.password}" />
</bean>
</beans>
Here it is my service class:
public class Userservice{
#Autowired
Database2IUserDAO immDao;
#Autowired
Database1IUserDAO iaaDao;
public User saveUser(fname,address){
User u = new User(); // This points Database-1 User table.
u.setFname(fname);
u.setAddress(address);
iaaDao.save(u);
User2 u2 = new User2(); // This points Database-2 User table.
u2.setFname(fname);
u2.setAddress(address);
immDao.save(u2);
}
}
Here is my Database1IUserDAO //This is an Interface
package com.xyz.dao;
public interface Database1IUserDAO {
public Object save(Object ob);
}
Here is my Database2IUserDAO //This is an another Interface for database2
package com.xyz.dao;
public interface Database2IUserDAO {
public Object save(Object ob);
}
** And this is finally DAO class for Database-1 and Database 2**
My both DAO class extends BaseDao class, that have Save() method that we are using to insert or save.
BaseDao.java
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.transaction.annotation.Transactional;
public class BaseDAO {
protected EntityManager entityManager;
#PersistenceContext
public void setEntityManager(EntityManager entityManager) {
this. entityManager = entityManager;
}
#Transactional
public Object save(Object ob) {
Object object = entityManager.merge(ob);
return object;
}
#Transactional
public void remove(Object ob) {
Object object = entityManager.merge(ob);
entityManager.remove(object);
}
#Transactional
public int update(String query) {
return entityManager.createQuery(query).executeUpdate();
}
}
Please help.
You have to use database specific Transaction Manager as you mentioned in your spring-context.xml file as below.
<bean id="transactionManager2" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="mmascentityManagerFactory" />
</bean>
You should create a save function in your DAO Class with database specific Transaction Manager as follows:
#Transactional(value="transactionManager2")
public Object save(Object ob) {
Object object = entityManager.merge(ob);
return object;
}
I hope it will work for you.
You seem to be using the same EntityManager (EM) from the BaseDAO for all your DAOs. Since you don't specify which TransactionManager the EM is using, it will default to this one:
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
... as noted in the documentation http://docs.spring.io/spring/docs/2.0.8/reference/transaction.html (find table 9.2)
If you want to write to another database, you will need to explicity tell Spring which one you want to use. See this answer as an example:
Spring multiple #Transactional datasources
It looks you are using the same datasource for both the persistence unit.
ie java:jboss/datasources/MySqlDS2
so it is inserting into only one DB which is corresponding to above data source mstly Mysql DB.
so add different datasource in both the persistence-unit , and that should help you to insert to both the databases.
it wont give any exception because one datasource that you are using might be valid datasource(i cant guarantee as we dont have data source information in your post).
let me know for any thing else.

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.

Multiple Entity Manager issue in Spring when using more than one datasource

I have two entity managers in my applicationContext.xml which corresponds to two different databases. I can easily query database1 with entityManager1, but when I try to access database2 with entityManager2, I am not getting any results. I am using Spring+Hibernate+JPA.
Here is my ApplicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans default-autowire="byName"
xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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">
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<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="database" value="INFORMIX" />
<property name="showSql" value="true" />
</bean>
</property>
<property name="persistenceUnitManager" ref="persistenceUnitManager" />
<property name="persistenceUnitName" value="PU1" />
</bean>
<bean id="entityManagerFactory2"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource2" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="INFORMIX" />
<property name="showSql" value="true" />
</bean>
</property>
<property name="persistenceUnitManager" ref="persistenceUnitManager" />
<property name="persistenceUnitName" value="PU2" />
</bean>
<!-- Data Sources -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.ibm.db2.jcc.DB2Driver" />
<property name="url"
value="jdbc:db2://HOST_NAME:PORT_NO/DB_NAME:INFORMIXSERVER=SERVER_NAME;DELIMIDENT=y;" />
<property name="username" value="username" />
<property name="password" value="password" />
<property name="minIdle" value="2" />
</bean>
<bean id="dataSource2" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.ibm.db2.jcc.DB2Driver" />
<property name="url"
value="jdbc:db2://HOST_NAME:PORT_NO/DB_NAME2:INFORMIXSERVER=SERVER_NAME;DELIMIDENT=y;" />
<property name="username" value="username" />
<property name="password" value="password" />
<property name="minIdle" value="2" />
</bean>
<bean
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"
lazy-init="false">
<property name="targetObject" ref="dataSource" />
<property name="targetMethod" value="addConnectionProperty" />
<property name="arguments">
<list>
<value>characterEncoding</value>
<value>UTF-8</value>
</list>
</property>
</bean>
<bean
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"
lazy-init="false">
<property name="targetObject" ref="dataSource2" />
<property name="targetMethod" value="addConnectionProperty" />
<property name="arguments">
<list>
<value>characterEncoding</value>
<value>UTF-8</value>
</list>
</property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"
scope="prototype">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="persistenceUnitManager"
class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="persistenceXmlLocations">
<list>
<value>classpath*:META-INF/persistence.xml</value>
<value>classpath*:META-INF/persistence2.xml</value>
</list>
</property>
<property name="dataSources">
<map>
<entry key="localDataSource" value-ref="dataSource" />
<entry key="dataSource2" value-ref="dataSource2" />
</map>
</property>
<property name="defaultDataSource" ref="dataSource" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="transactionManager2" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory2" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<tx:annotation-driven transaction-manager="transactionManager2" />
<!-- MORE Action and DAO beans -->
</beans>
This is my service layer code which works fine with enityManager1:
#Transactional
public class StatesDAO implements IStatesDAO {
private EntityManager em;
#PersistenceContext(unitName = "PU1")
public void setEntityManager(EntityManager em) {
this.em = em;
}
private EntityManager getEntityManager() {
return em;
}
#SuppressWarnings("unchecked")
public List<States> findAll() {
logger.info("finding all States instances");
try {
final String queryString = "select model from States model";
Query query = getEntityManager().createQuery(queryString);
return query.getResultList();
} catch (RuntimeException re) {
throw re;
}
}
}
My two persitence.xml files look like this:
<?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="PU1" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.jpa.entity.States</class>
</persistence-unit>
</persistence>
and
<?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="PU2" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.jpa.other.entity.States</class>
</persistence-unit>
</persistence>
If I change my service layer (as shown below), I get no results. Basically the size of the list is zero:
#Transactional
public class StatesDAO implements IStatesDAO {
private EntityManager em;
#PersistenceContext(unitName = "PU2")
public void setEntityManager(EntityManager em) {
this.em = em;
}
private EntityManager getEntityManager() {
return em;
}
#SuppressWarnings("unchecked")
public List<com.jpa.other.entity.States> findAll() {
logger.info("finding all States instances");
try {
final String queryString = "select model from States model";
Query query = getEntityManager().createQuery(queryString);
return query.getResultList();
} catch (RuntimeException re) {
throw re;
}
}
}
So basically you can see is that I have two entities(States) with exactly same structure and in order to differentiate from each other I have put them into separate packages
According to my knowledge I am not doing anything crazy here but still it doesn't seem to be working. How is this problem caused and how can I solve this?
Follow-up: One thing I forgot to mention is that even though there are two different databases but the database server name is same. I don't know if this could be a useful information.So thought of sharing it.
This is the exception I am getting now:
16:24:44,732 INFO [STDOUT] Hibernate: select state0_.state as col_0_0_ from states state0_
16:24:44,753 WARN [JDBCExceptionReporter] SQL Warning: 36106, SQLState: 01I01
16:24:44,753 WARN [JDBCExceptionReporter] IDS SQL Warning: SQLCODE=36106, SQLSTATE=01I01, SQLERRMC=0;819;informix;;IDS/NT32;1;1;0;819;0;, DRIVER=4.7.85
I've hit the same exact issue, but with multiple Hibernate session factories: 2 DBs with the same structure, I didn't want to have 2 identical sets of DAOs, etc. While my experience was with Hibernate, I suspect you could use the same solution: Spring's AbstractRoutingDataSource. It allows you to configure your app to determine at runtime which data source to use, based on a value set on the ThreadLocal. See http://blog.springsource.com/2007/01/23/dynamic-datasource-routing/ for an introduction. What ends up happening is that the dataSource ref in your factory will point not at a hard-coded dataSource bean, but at the AbstractRoutingDataSource. To set the toggle per-thread, use an #Aspect to determine which DB to hit.

Categories