How to share Entity classes across multiple Persistence Unit? - jpa

How to share Entity classes across multiple Persistence Unit?
I have 2 MySql databases (dbOne, dbTWO) with the same table "users"
I would like to have an Entity class like this :
#Entity
public class User {
...
...
}
shared between the 2 PU (of dbONE and dbTWO).. (eclipse.persistence)
i tried with :
<persistence-unit name="one_PU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.model.User</class>
<validation-mode>NONE</validation-mode>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<shared-cache-mode>NONE</shared-cache-mode>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/dbONE"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="*****"/>
<property name="javax.persistence.jdbc.password" value="******"/>
<property name="eclipselink.jdbc.batch-writing" value="JDBC"/>
<property name="eclipselink.jdbc.batch-writing.size" value="1000"/>
<property name="eclipselink.jdbc.cache-statements" value="false"/>
<property name="eclipselink.cache.shared.default" value="false"/>
</properties>
</persistence-unit>
<persistence-unit name="two_PU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.model.User</class>
<validation-mode>NONE</validation-mode>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<shared-cache-mode>NONE</shared-cache-mode>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/dbTWO"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="*****"/>
<property name="javax.persistence.jdbc.password" value="*****"/>
<property name="eclipselink.jdbc.batch-writing" value="JDBC"/>
<property name="eclipselink.jdbc.batch-writing.size" value="1000"/>
<property name="eclipselink.jdbc.cache-statements" value="false"/>
<property name="eclipselink.cache.shared.default" value="false"/>
</properties>
</persistence-unit>
without success..
Is it possible?..how can i do that?

Related

Hibernate timeout does not work in postgresql 10

persistence.xml:
<properties>
<property name="showSql" value="true"/>
<property name="hibernate.dialect" value="${hibernate.dialect:org.hibernate.dialect.Oracle10gDialect}"/>
<propertyname="hibernate.connection.datasource"value="java:/alarmmgr/alarmMonitorDB"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="false"/>
<property name="hibernate.use_sql_comments" value="false"/>
<property name="hibernate.jdbc.wrap_result_sets" value="false"/>
<property name="hibernate.hibernate.cache.use_query_cache" value="true"/>
<property name="javax.persistence.query.timeout" value="1" />
</properties>
query:
em.createQuery(query).setHint("javax.persistence.query.timeout", 1)
.setFirstResult(payload.getStart())
.setMaxResults(payload.getSize() > MAX_FETCH ? MAX_FETCH : payload.getSize())
.getResultList()
The query returned 7 thousand rows... but the timeout does not work.
The JDBC Postgresql driver does not work with the property javax.persistence.query.timeout,
so i did an workaround.
em.unwrap(Session.class).doWork(connection -> {
long maxTimeOutMil = TimeUnit.SECONDS.toMillis(MAX_TIMEOUT);
connection.createStatement().execute("set statement_timeout = " + maxTimeOutMil);
});

JBPM6 project connect to mysql failed

i installed jbpm6 and mysql,i used PoolingDataSource to start BD,but always unable to find'squenses' tables,i kown it's hibernate'dialect problem,and i want to use persistence.xml to start .
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<persistence
version="2.0"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_2_0.xsd"
xmlns:orm="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="com.test.test" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/jbpm-ds</jta-data-source>
<mapping-file>META-INF/JBPMorm.xml</mapping-file>
<mapping-file>META-INF/Taskorm.xml</mapping-file>
<class>org.jbpm.persistence.processinstance.ProcessInstanceInfo</class>
<class>org.drools.persistence.info.SessionInfo</class>
<class>org.drools.persistence.info.WorkItemInfo</class>
<class>org.jbpm.process.audit.ProcessInstanceLog</class>
<class>org.jbpm.process.audit.NodeInstanceLog</class>
<class>org.jbpm.process.audit.VariableInstanceLog</class>
<class>org.jbpm.persistence.correlation.CorrelationKeyInfo</class>
<class>org.jbpm.persistence.correlation.CorrelationPropertyInfo</class>
<!-- manager -->
<class>org.jbpm.runtime.manager.impl.jpa.ContextMappingInfo</class>
<class>org.jbpm.services.task.impl.model.AttachmentImpl</class>
<class>org.jbpm.services.task.impl.model.ContentImpl</class>
<class>org.jbpm.services.task.impl.model.BooleanExpressionImpl</class>
<class>org.jbpm.services.task.impl.model.CommentImpl</class>
<class>org.jbpm.services.task.impl.model.DeadlineImpl</class>
<class>org.jbpm.services.task.impl.model.CommentImpl</class>
<class>org.jbpm.services.task.impl.model.DeadlineImpl</class>
<class>org.jbpm.services.task.impl.model.DelegationImpl</class>
<class>org.jbpm.services.task.impl.model.EscalationImpl</class>
<class>org.jbpm.services.task.impl.model.GroupImpl</class>
<class>org.jbpm.services.task.impl.model.I18NTextImpl</class>
<class>org.jbpm.services.task.impl.model.NotificationImpl</class>
<class>org.jbpm.services.task.impl.model.EmailNotificationImpl</class>
<class>org.jbpm.services.task.impl.model.EmailNotificationHeaderImpl</class>
<class>org.jbpm.services.task.impl.model.PeopleAssignmentsImpl</class>
<class>org.jbpm.services.task.impl.model.ReassignmentImpl</class>
<class>org.jbpm.services.task.impl.model.TaskImpl</class>
<class>org.jbpm.services.task.impl.model.TaskDataImpl</class>
<class>org.jbpm.services.task.impl.model.UserImpl</class>
<!--BAM for task service -->
<class>org.jbpm.services.task.impl.model.BAMTaskSummaryImpl</class>
<properties>
<property name="hibernate.max_fetch_depth" value="3"/>
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<!-- BZ 841786: AS7/EAP 6/Hib 4 uses new (sequence) generators which seem to cause problems -->
<property name="hibernate.id.new_generator_mappings" value="false" />
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.username" value="jbpm"/>
<property name="hibernate.connection.password" value="jbpm"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/jbpm"/>
<property name="hibernate.cglib.use_reflection_optimizer" value="true"/>
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.BitronixJtaPlatform" />
</properties>
</persistence-unit>
</persistence>
but the error is that:
​Exception in thread "main" javax.persistence.PersistenceException: [PersistenceUnit: org.jbpm.persistence.jpa] Unable to build EntityManagerFactory
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:925)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:900)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:59)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:63)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:47)
at test.test.createRuntimeManager(test.java:71)
at test.test.main(test.java:37)
Caused by: org.hibernate.service.jndi.JndiException: Unable to lookup JNDI name [jdbc/jbpm-ds]
at org.hibernate.service.jndi.internal.JndiServiceImpl.locate(JndiServiceImpl.java:68)
at org.hibernate.service.jdbc.connections.internal.DatasourceConnectionProviderImpl.configure(DatasourceConnectionProviderImpl.java:116)
at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:85)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:184)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:156)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAccess(JdbcServicesImpl.java:223)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:89)
at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:85)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:184)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:156)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1827)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1785)
at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:96)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:915)
... 6 more
Caused by: javax.naming.NameNotFoundException: unable to find a bound object at name 'jdbc/jbpm-ds'
at bitronix.tm.jndi.BitronixContext.lookup(BitronixContext.java:83)
at bitronix.tm.jndi.BitronixContext.lookup(BitronixContext.java:67)
at javax.naming.InitialContext.lookup(Unknown Source)
at org.hibernate.service.jndi.internal.JndiServiceImpl.locate(JndiServiceImpl.java:65)
... 19 more
i don't kown what i lose

EntityTransaction rollback

I use EJB to insert/update data to the database and I have this problem. My commit only works with updating(merge), but doesn't rollback inserts(persist). Even more, my inserts(persist) happen before transaction commit.
my persistence unit:
<persistence-unit name="bpmBeans_RESOURCE_LOCAL" transaction-type="RESOURCE_LOCAL">
<jta-data-source>java:jboss/datasources/java_orgstruct</jta-data-source>
<properties>
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.connection.useUnicode" value="true"/>
<property name="hibernate.connection.characterEncoding" value="UTF-8"/>
<property name="hibernate.connection.CharSet" value="utf8"/>
<property name="hibernate.cache.use_second_level_cache" value="true" />
<property name="hibernate.cache.use_query_cache" value="true" />
<property name="hibernate.transaction.factory_class" value="org.hibernate.transaction.JTATransactionFactory" />
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.JBossTransactionManagerLookup"/>
<property name="hibernate.connection.autocommit" value="false"/>
</properties>
</persistence-unit>
how i inject entity manager factory
#PersistenceUnit(unitName="bpmBeans_RESOURCE_LOCAL")
public EntityManagerFactory emf;
what happens with the code
EntityManager em = emf.createEntityManager();
EntityTransaction ets = em.getTransaction();
ets.begin();
Process newObj = new Process();
em.persist(newObj); //data gets inserted at this moment, not at commit
...
...
if(allgood){
ets.commit();// now update(merge, setters on managed entities) would happend.
} else {
ets.rollback(); // this would rollback the updates, but not the insert
}
Any ideas what to try? I guess I'm just understanding some JPA concepts badly.
EDIT:
Datasource code. Datasource is described in WEB-INF/mysql-ds.xml file . Driver .jar is in JBoss deployments.
<?xml version="1.0" encoding="UTF-8"?>
<datasources xmlns="http://www.jboss.org/ironjacamar/schema">
<datasource jndi-name="java:jboss/datasources/java_orgstruct" pool-name="MySQLPool">
<connection-url>jdbc:mysql://192.168.150.141/organisation_model</connection-url>
<connection-property name="zeroDateTimeBehavior">convertToNull</connection-property>
<connection-property name="characterEncoding">utf8</connection-property>
<driver>mysql-connector-java-5.1.28-bin.jar</driver>
<security>
<user-name></user-name>
<password></password>
</security>
</datasource>
</datasources>

join table between two persistance unit

join 2 table between 2 persistance unit
<persistence-unit name="oltpJPA">
<class>entity.timetable</class>
<class>entity.facultyleave</class>
<properties>
<property name="openjpa.jdbc.Schema" value="OLTP" />
<property name="openjpa.ConnectionDriverName"value="com.ibm.db2.jcc.DB2Driver"/>
<property name="openjpa.ConnectionURL" value="jdbc:db2://172.16.1.7:50000/OLTPDB:retrieveMessagesFromServerOnGetMessage=true;"/>
<property name="openjpa.ConnectionUserName" value="administrator"/>
<property name="openjpa.ConnectionPassword" value="server"/>
</properties>
</persistence-unit>
<persistence-unit name="oltpJPAabs">
<class>property.Properties</class>
<class>entity.StudentAbsenteseDate</class>
<class>entity.StudentAbsenteseLecture</class>
<properties>
<property name="openjpa.jdbc.Schema" value="OLTP" />
<property name="openjpa.ConnectionDriverName" value="com.ibm.db2.jcc.DB2Driver"/>
<property name="openjpa.ConnectionURL" value="jdbc:db2://172.16.1.9:50000/OLTPDB:retrieveMessagesFromServerOnGetMessage=true;"/>
<property name="openjpa.ConnectionUserName" value="administrator"/>
<property name="openjpa.ConnectionPassword" value="lenovo"/>
</properties>
</persistence-unit></persistence>
not able to manage the foreign key between studentabsenteselecture and timetable

EntityManager.merge() is not updating the database

I am trying to update the user_info table with the new password using EntityManager.merge(), but it is not getting committed. Below is my code:
app-cofig.xml:
<!-- Application Message Bundle -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages" />
<property name="cacheSeconds" value="300" />
</bean>
<bean id="loginValidator" class="com.sbi.llms.validator.LoginValidator"/>
<bean id="loginProcessor" class="com.sbi.llms.processor.LoginProcessor">
<property name="userDao" ref="userDao"/>
</bean>
<!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean id="forgetProcessor" class="com.test.ForgetPasswordProcessor">
<property name="forgetDao" ref="forgetDao"/>
</bean>
<bean name="/popup_forgot_password.html" class="com.test.ForgetPasswordController">
<property name="processor" ref="forgetProcessor"/>
<property name="commandClass" value="com.test.ForgetPasswordDTO"/>
<property name="commandName" value="btn_reset"/>
<property name="formView" value="popup_forgot_password"/>
<property name="successView" value="popup_forgot_password"/>
<property name="validator">
<bean class="com.test.LoginValidator"/>
</property>
</bean>
<bean id="myDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:#10.0.27.105:1521/LLMSDB1"/>
<property name="username" value="llms"/>
<property name="password" value="llms12"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" p:entityManagerFactory-ref="entityManagerFactory" />
<bean id="entityManager" class="org.springframework.orm.jpa.support.SharedEntityManagerBean" p:entityManagerFactory-ref="entityManagerFactory" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="persistenceUnitName" value="cccPersistenceUnit" />
<property name="jpaDialect" ref="jpaDialect" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
<property name="databasePlatform" value="org.eclipse.persistence.platform.database.OraclePlatform"/>
<property name="showSql" value="true"/>
</bean>
</property>
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
</bean>
<bean id="baseJPADao" class="com.sbi.llms.dao.jpa.BaseJPADAO">
<property name="entityManager" ref="entityManager"/>
</bean>
<bean id="userDao" class="com.sbi.llms.dao.UserDAO">
<property name="entityManager" ref="entityManager"/>
</bean>
<bean id="forgetDao" class="com.test.ForgetPasswordDAO">
<property name="entityManager" ref="entityManager"/>
</bean>
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect" />
persistance.xml
<?xml version="1.0" encoding="UTF-8" ?>
<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" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="cccPersistenceUnit" transaction-type="RESOURCE_LOCAL"> <!-- "RESOURCE_LOCAL" -->
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<mapping-file>META-INF/LoginModel.xml</mapping-file>
<mapping-file>META-INF/eclipselink-orm.xml</mapping-file>
<class>com.sbi.llms.model.LoginModel</class>
<class>com.test.ForgetPasswordModel</class>
<properties>
<!-- Configure cache size. -->
<property name="eclipselink.cache.size.default" value="1000" />
<!-- Configure simple SQL logging for demonstration. -->
<property name="eclipselink.logging.level" value="FINE" />
<property name="eclipselink.logging.thread" value="false" />
<property name="eclipselink.logging.session" value="false" />
<property name="eclipselink.logging.exceptions" value="false" />
<property name="eclipselink.logging.timestamp" value="false" />
</properties>
</persistence-unit>
</persistence>
Here is my DAO
public class ForgetPasswordDAO {
private Vector loginResult = null;
private int resultTrue = 1;
private int resultFalse = 0;
protected EntityManager entityManager;
JpaEntityManager jpaEntityManager;
public ForgetPasswordDAO() {
}
public EntityManager getEntityManager() {
return entityManager;
}
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
public Integer fetchUser(ForgetPasswordModel model) throws Exception {
try {
ForgetPasswordDTO DTO ;
if(model == null) {
throw new Exception("102");
}
Integer result = 0;
String userName = model.getUser_id();
String dob = model.getDob();
System.out.println("UserDTO " + model.getUser_id() + " "
+ model.getDob());
ForgetPasswordModel forgetModel = null;
System.out.println(entityManager.isOpen()+">>");
forgetModel = entityManager.find(ForgetPasswordModel.class, model.getUser_id());
entityManager.close();
System.out.println("UserDAO " + forgetModel.getUser_id() + " DOB "
+ forgetModel.getDob()+" EMAIL_ID "+forgetModel.getEmail_id()+" PASSWORD "+forgetModel.getPasswd());
if(model.getDob().equals(forgetModel.getDob())) {
System.out.println("USER VALID , CAN PROCEED WITH PASSWORD RESET");
String passwd = GenerateRandomPassword.generateRandomPassword();
System.out.println("generated password is" +passwd);
entityManager.getTransaction().begin();
forgetModel.setPasswd(passwd);
entityManager.merge(forgetModel);
entityManager.getTransaction().commit();
System.out .println("updated password is "+forgetModel.getPasswd());
String email=forgetModel.getEmail_id();
ForgetPasswordSendMail.SendMail( email, passwd);
result=1;
}
else
{
System.out.println("USER InVALID , Please Provide Valid Data");
}
return result;
} catch (Exception e) {
throw new Exception("103", e);
}
}
}
When I run the above code I get the following error:
java.lang.IllegalStateException: Not allowed to create transaction on shared EntityManager - use Spring transactions or EJB CMT instead
org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:198)
com.sun.proxy.$Proxy6.getTransaction(Unknown Source)
com.test.ForgetPasswordDAO.fetchUser(ForgetPasswordDAO.java:81)
com.test.ForgetPasswordProcessor.execute(ForgetPasswordProcessor.java:52)
com.test.ForgetPasswordController.onSubmit(ForgetPasswordController.java:56)
org.springframework.web.servlet.mvc.SimpleFormController.processFormSubmission(SimpleFormController.java:272)
org.springframework.web.servlet.mvc.AbstractFormController.handleRequestInternal(AbstractFormController.java:268)
org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:153)
org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:48)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
Since you are using Spring, you need to use Spring transactions, not JPA transactions.
You need to declare the transaction in Spring, or access the EntityManager directly, not through Spring.