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);
});
Related
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?
I'm trying to test spring batch using dbunit but when batch runs HibernateCursorItemReader it doesn't see temporary created objects in the db. But if I create entities using HibernateDaoSupport everything is fine and I can work with test data. Does anybody know how to force batch see my test entities?
My test classes:
#RunWith(SpringEasyMockRunner.class)
#TestExecutionListeners({DependencyInjectionTestExecutionListener.class, TransactionalTestExecutionListener.class, DbUnitTestExecutionListener.class})
#Transactional
#ContextConfiguration({"classpath:/integration-test-context.xml"})
#DbUnitConfiguration(
databaseConnection = {"dbUnitDatabaseConnection"}
)
public abstract class BaseIT implements ApplicationContextAware {
...
}
#RunWith(SpringEasyMockRunner.class)
#ContextConfiguration("classpath:/sopl-test-context.xml")
#DatabaseSetup(value = "classpath:data/SoplTestDataIT.xml", type = DatabaseOperation.CLEAN_INSERT)
#Slf4j
public class SoplOrderTestIT extends BaseIT {
...
}
And configs integration-test-context.xml:
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" lazy-init="true" destroy-method="close">
<property name="driverClass" value="${hibernate.driver}"/>
<property name="jdbcUrl" value="${hibernate.connection.url}"/>
<property name="user" value="${hibernate.connection.username}"/>
<property name="password" value="${hibernate.connection.password}"/>
<property name="initialPoolSize" value="${c3p0.initialPoolSize:1}"/>
<property name="minPoolSize" value="${c3p0.minPoolSize:0}"/>
<property name="maxPoolSize" value="${c3p0.maxPoolSize:200}"/>
<property name="maxIdleTime" value="${c3p0.maxIdleTime:120}"/>
<property name="maxStatementsPerConnection" value="${c3p0.maxStatementsPerConnection:100}"/>
<property name="checkoutTimeout" value="${c3p0.checkoutTimeout:30000}"/>
<property name="idleConnectionTestPeriod" value="${c3p0.idleConnectionTestPeriod:3600}"/>
<property name="unreturnedConnectionTimeout" value="${c3p0.unreturnedConnectionTimeout:7200}"/>
<property name="debugUnreturnedConnectionStackTraces"
value="${c3p0.debugUnreturnedConnectionStackTraces:true}"/>
</bean>
<bean name="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="namingStrategy">
<bean class="org.hibernate.cfg.DefaultComponentSafeNamingStrategy"/>
</property>
<property name="configLocations" value="classpath:/hibernate/*-hibernate.cfg.xml"/>
<property name="hibernateProperties">
<props merge="true">
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</prop>
<prop key="hibernate.cache.use_second_level_cache">false</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql:false}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql:false}</prop>
<prop key="hibernate.use_sql_comments">${hibernate.use_sql_comments:false}</prop>
<prop key="hibernate.generate_statistics">${hibernate.generate_statistics:false}</prop>
<prop key="hibernate.hbm2ddl.auto"/>
<prop key="hibernate.search.autoregister_listeners">false</prop>
</props>
</property>
</bean>
<!-- transaction manager for hibernate -->
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager" primary="true">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- spring-test-dbunit configuration: -->
<bean id="dbUnitDatabaseConfig" class="com.github.springtestdbunit.bean.DatabaseConfigBean">
<property name="qualifiedTableNames" value="true"/>
<property name="metadataHandler">
<bean class="org.dbunit.ext.mysql.MySqlMetadataHandler"/>
</property>
<property name="datatypeFactory">
<bean class="org.dbunit.ext.mysql.MySqlDataTypeFactory"/>
</property>
</bean>
<bean id="dbUnitDatabaseConnection"
class="com.github.springtestdbunit.bean.DatabaseDataSourceConnectionFactoryBean">
<property name="databaseConfig" ref="dbUnitDatabaseConfig"/>
<property name="dataSource" ref="dataSource"/>
</bean>
...
I am setting the maxItemCount property of JdbcPagingItemReader.
I am setting it to 200 but I am getting read/processed/written of 203, 205.
Most of the time I am getting 200 but I get around 200+ commonly.
Why is this happening??
I've checked and there are no same timestamp value for the the sortkey in the 203-205 processed and the max.item.count field is not present in the batch_execution_context entry in the database table.
There is a JdbcPagingItemReader.read.count.max field but it is set to 200.
I am using oracle.
<bean id="batchReader" class="org.springframework.batch.item.database.JdbcPagingItemReader" scope="step">
<property name="dataSource" ref="myDataSource"/>
<property name="queryProvider">
<bean class="org.springframework.batch.item.database.support.SqlPagingQueryProviderFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="selectClause" value="select *" />
<property name="fromClause" value="from TRANSACTION" />
<property name="whereClause" value="where STATUS = 'OK' and TYPE = 200 " />
<property name="sortKey" value="TRANSACTION_TIMESTAMP"/>
</bean>
</property>
<!-- Inject via the ExecutionContext in rangePartitioner -->
<property name="parameterValues">
<map>
</map>
</property>
<property name="maxItemCount" value="200"/>
<property name="pageSize" value="50"/>
<property name="rowMapper">
<bean class="com.mappers.TransactionMapper" scope="step"/>
</property>
</bean>
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
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.