Spring data - modifying query concurrency - java

I have the following repository:
public interface PlayerRealBalanceRepository extends JpaRepository<PlayerRealBalance, Long> {
#Modifying
#Query("update PlayerRealBalance balance set balance.balance = (balance.balance + ?1) where balance.id = ?2")
public void increaseBalance(long amount, long balanceId);
}
My Question - is this query thread safe? what if 2 concurrent queries like this are executed exactly at the same time? Do i have to use a lock method in order for it to work properly?
Thanks!

It will run into ACID(Atomicity, Consistency, Isolation, Durability) problem. Hence better to use transaction please refer spring transaction management here For your reference here is the log(self explanatory) what happens if you implement transaction management(though I use Mybatis)
2014-02-11 16:48:21,008 [main] DEBUG o.s.j.d.DataSourceTransactionManager - Switching JDBC Connection [jdbc:oracle:thin] to manual commit
2014-02-11 16:48:21,013 [main] DEBUG org.mybatis.spring.SqlSessionUtils - Creating a new SqlSession
2014-02-11 16:48:21,021 [main] DEBUG org.mybatis.spring.SqlSessionUtils - Registering transaction synchronization for SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession#16a23cf]
2014-02-11 16:48:21,091 [main] DEBUG o.m.s.t.SpringManagedTransaction - JDBC Connection [jdbc:oracle:thin:] will be managed by Spring
// does the db operation
2014-02-11 16:48:21,792 [main] DEBUG org.mybatis.spring.SqlSessionUtils - Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession#16a23cf]
2014-02-11 16:48:21,792 [main] DEBUG o.s.j.d.DataSourceTransactionManager - Initiating transaction commit
2014-02-11 16:48:21,792 [main] DEBUG o.s.j.d.DataSourceTransactionManager - Committing JDBC transaction on Connection [jdbc:oracle:thin:]
2014-02-11 16:48:21,792 [main] DEBUG org.mybatis.spring.SqlSessionUtils - Transaction synchronization committing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession#16a23cf]
2014-02-11 16:48:21,792 [main] DEBUG org.mybatis.spring.SqlSessionUtils - Transaction synchronization closing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession#16a23cf]
2014-02-11 16:48:21,792 [main] DEBUG o.s.jdbc.datasource.DataSourceUtils - Resetting isolation level of JDBC Connection [jdbc:oracle:thin:] to 2
2014-02-11 16:48:21,792 [main] DEBUG o.s.j.d.DataSourceTransactionManager - Releasing JDBC Connection [jdbc:oracle:thin:#] after transaction
2014-02-11 16:48:21,792 [main] DEBUG o.s.jdbc.datasource.DataSourceUtils - Returning JDBC Connection to DataSource

Related

REQUIRES_NEW: Spring outer transaction rollbacks also instead of persisting when inner rollbacks

I have a Spring Boot application where I have a thin layer between the Controller and the Service which's only purpose it to try-catch and if an exception is thrown, to persist the failed entity with a JpaRepository, for subsequent inspection.
I designed my "interceptor" like:
#Transactional
public void upload(byte[] bytes) {
try {
service.upload(bytes);
} catch (Exception e) {
failRepo.save(new Failure(bytes, e)); // code trimmed for brevity
throw e;
}
}
And my service method looks like:
#Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
public void upload(byte[] bytes);
What I expect is that, in case of an exception thrown in the service, the inner transaction will be rollbacked, the exception will pop out and the outer transaction will persist my data, but the hibernate logs show that for some reason the outer transaction also rollbacks and the failure data is not persisted.
Do I need another propagation level on the outer layer also?
Edit: the relevant logs
o.s.o.h.HibernateTransactionManager : Creating new transaction with name [com.company.interceptor.upload]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
o.s.o.h.HibernateTransactionManager : Opened new Session [SessionImpl(480607911<open>)] for Hibernate transaction
o.h.e.t.internal.TransactionImpl : On TransactionImpl creation, JpaCompliance#isJpaTransactionComplianceEnabled == false
o.h.e.t.internal.TransactionImpl : begin
o.s.o.h.HibernateTransactionManager : Exposing Hibernate transaction as JDBC [org.springframework.orm.hibernate5.HibernateTransactionManager$$Lambda$1317/0x0000000800d0c440#52318830]
o.s.o.h.HibernateTransactionManager : Found thread-bound Session [SessionImpl(480607911<open>)] for Hibernate transaction
o.s.o.h.HibernateTransactionManager : Suspending current transaction, creating new transaction with name [com.company.service.upload]
o.s.o.h.HibernateTransactionManager : Opened new Session [SessionImpl(1041560268<open>)] for Hibernate transaction
o.h.e.t.internal.TransactionImpl : On TransactionImpl creation, JpaCompliance#isJpaTransactionComplianceEnabled == false
o.h.e.t.internal.TransactionImpl : begin
o.s.o.h.HibernateTransactionManager : Exposing Hibernate transaction as JDBC [org.springframework.orm.hibernate5.HibernateTransactionManager$$Lambda$1317/0x0000000800d0c440#778c9da3]
------ other irrelevant for us logs
o.s.o.h.HibernateTransactionManager : Initiating transaction rollback
o.s.o.h.HibernateTransactionManager : Rolling back Hibernate transaction on Session [SessionImpl(1041560268<open>)]
o.h.e.t.internal.TransactionImpl : rolling back
o.s.o.h.HibernateTransactionManager : Closing Hibernate Session [SessionImpl(1041560268<open>)] after transaction
o.s.o.h.HibernateTransactionManager : Resuming suspended transaction after completion of inner transaction
stomAnnotationTransactionAttributeSource : Adding transactional method 'save' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
o.s.o.h.HibernateTransactionManager : Found thread-bound Session [SessionImpl(480607911<open>)] for Hibernate transaction
o.s.o.h.HibernateTransactionManager : Participating in existing transaction
org.hibernate.engine.spi.ActionQueue : Executing identity-insert immediately
org.hibernate.SQL : insert into failure_table (content_type, created_time, exception_message, bytes, user_agent) values (?, ?, ?, ?, ?)
o.h.id.IdentifierGeneratorHelper : Natively generated identity: 15
o.h.r.j.i.ResourceRegistryStandardImpl : HHH000387: ResultSet's statement was not registered
o.s.o.h.HibernateTransactionManager : Initiating transaction rollback
o.s.o.h.HibernateTransactionManager : Rolling back Hibernate transaction on Session [SessionImpl(480607911<open>)]
o.h.e.t.internal.TransactionImpl : rolling back
o.s.o.h.HibernateTransactionManager : Closing Hibernate Session [SessionImpl(480607911<open>)] after transaction
Problem solution helped found by: https://stackoverflow.com/a/7125918/3214777.
The problem was that Spring rollbacks by default on runtime exception so I needed an
#Transactional(noRollbackFor = Exception.class)
on my interceptor to get it going as I would've expected.

Spring boot problem with #Async and #Transactional

I have a few milions of records and I migrate it from one Oracle DB to another. We have performance problem and after discussing with my colleagues I decided to process data multithread.
We have the following artifacts:
Spring boot 2.1.6.RELEASE
HikariCP 3.2.0
Hibernate 5.3.10.Final
JDK 11.0.2
OJDBC8 12.2.0.1
I have Service class annotated #Service and inside the class is method
#Async("threadPoolTaskExecutor")
#Transactional(propagation = Propagation.REQUIRES_NEW)
public void processMigration(int from, int to) {
int progressInterval = to - from;
ProgressBar progressBar = new ProgressBar("Progress " + Thread.currentThread().getName(), progressInterval, ProgressBarStyle.UNICODE_BLOCK);
try (Stream<SomeEntity> entityStream = someEntityRepository.streamAllInInterval(from, to)) {
progressBar.start();
entityStream.forEach(entity -> progressBar.step());
progressBar.stop();
} catch (Exception e) {
progressBar.stop();
throw e;
}
}
inside the foreach there will be some logic for processing data and this service is injected into another class call it Migrator (containing injected ThreadPoolTaskExecutor) with the following method:
public void migrate() {
crimeService.processMigration(0, 500000);
crimeService.processMigration(500000, 1000000);
}
and my SpringBootApplication class (main configuration):
#SpringBootApplication
#EnableAsync
#EnableTransactionManagement
public class MigrationApplication {
public static void main(String[] args) {
SpringApplication.run(MigrationApplication.class, args);
}
#Bean("threadPoolTaskExecutor")
public TaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(25);
executor.setQueueCapacity(30);
executor.afterPropertiesSet();
return executor;
}
}
application.yaml looks like this:
spring:
jpa:
properties:
hibernate:
jdbc:
batch_size: 100
fetch_size: 400
dialect: org.hibernate.dialect.Oracle12cDialect
order_inserts: true
order_updates: true
datasource:
url: jdbc:oracle:thin::1521:something
username: username
password: password
hikari:
maximum-pool-size: 10
leak-detection-threshold: 30000
driver-class-name: oracle.jdbc.OracleDriver
I supposed that when I ran the mentioned code then Hikari will create 2 connections, because I have called twice the method processMigration() annotated with #Transactional. I saw in log that it created only at the begining, but when the one of the threads waiting to another then there was only one connection as active. My computer has available 4 cores, so I would expect that with the HW problem does not exist. I understand why there is only one active connection because there is only one thread running, but why the second thread waiting I cannot figure out. Please help and If someone have better approach how to migrate data than I chose, I appriciate your suggestion.
UPDATE
I found out that the JpaTransactionManager creates the transaction for both threads, but one transaction is committed immediately at the begining. When the second thread had finished the task, it has not finished the previous task.
2019-08-15 15:02:39.707 DEBUG 3939 --- [ main] o.s.orm.jpa.JpaTransactionManager : Creating new transaction with name [org.springframework.data.jpa.repository.support.SimpleJpaRepository.count]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly
2019-08-15 15:02:39.707 DEBUG 3939 --- [ main] o.s.orm.jpa.JpaTransactionManager : Opened new EntityManager [SessionImpl(1773290233<open>)] for JPA transaction
2019-08-15 15:02:39.717 DEBUG 3939 --- [ main] o.s.orm.jpa.JpaTransactionManager : Exposing JPA transaction as JDBC [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle#698ef9d1]
2019-08-15 15:02:40.156 DEBUG 3939 --- [ main] o.s.orm.jpa.JpaTransactionManager : Initiating transaction commit
2019-08-15 15:02:40.157 DEBUG 3939 --- [ main] o.s.orm.jpa.JpaTransactionManager : Committing JPA transaction on EntityManager [SessionImpl(1773290233<open>)]
2019-08-15 15:02:40.163 DEBUG 3939 --- [ main] o.s.orm.jpa.JpaTransactionManager : Closing JPA EntityManager [SessionImpl(1773290233<open>)] after transaction
Migrating 1799449 CRIMES
2019-08-15 15:02:40.186 DEBUG 3939 --- [lTaskExecutor-2] o.s.orm.jpa.JpaTransactionManager : Creating new transaction with name [com.aliter.mvsmigration.dvs.service.CrimeServiceImpl.processMigration]: PROPAGATION_REQUIRES_NEW,ISOLATION_DEFAULT
2019-08-15 15:02:40.186 DEBUG 3939 --- [lTaskExecutor-1] o.s.orm.jpa.JpaTransactionManager : Creating new transaction with name [com.aliter.mvsmigration.dvs.service.CrimeServiceImpl.processMigration]: PROPAGATION_REQUIRES_NEW,ISOLATION_DEFAULT
TASK duration: 830ms
2019-08-15 15:02:40.187 DEBUG 3939 --- [lTaskExecutor-2] o.s.orm.jpa.JpaTransactionManager : Opened new EntityManager [SessionImpl(346995150<open>)] for JPA transaction
2019-08-15 15:02:40.187 DEBUG 3939 --- [lTaskExecutor-1] o.s.orm.jpa.JpaTransactionManager : Opened new EntityManager [SessionImpl(1848267920<open>)] for JPA transaction
2019-08-15 15:02:40.187 DEBUG 3939 --- [lTaskExecutor-2] o.s.orm.jpa.JpaTransactionManager : Exposing JPA transaction as JDBC [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle#1a69552b]
2019-08-15 15:02:40.188 DEBUG 3939 --- [ main] o.s.orm.jpa.JpaTransactionManager : Creating new transaction with name [org.springframework.data.jpa.repository.support.SimpleJpaRepository.save]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
2019-08-15 15:02:40.189 DEBUG 3939 --- [ main] o.s.orm.jpa.JpaTransactionManager : Opened new EntityManager [SessionImpl(282270616<open>)] for JPA transaction
2019-08-15 15:02:40.191 DEBUG 3939 --- [lTaskExecutor-1] o.s.orm.jpa.JpaTransactionManager : Exposing JPA transaction as JDBC [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle#22c0dffa]
2019-08-15 15:02:40.192 DEBUG 3939 --- [ main] o.s.orm.jpa.JpaTransactionManager : Exposing JPA transaction as JDBC [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle#817e0aa]
2019-08-15 15:02:40.212 DEBUG 3939 --- [ main] o.s.orm.jpa.JpaTransactionManager : Initiating transaction commit
2019-08-15 15:02:40.214 DEBUG 3939 --- [ main] o.s.orm.jpa.JpaTransactionManager : Committing JPA transaction on EntityManager [SessionImpl(282270616<open>)]
2019-08-15 15:02:40.229 DEBUG 3939 --- [ main] o.s.orm.jpa.JpaTransactionManager : Closing JPA EntityManager [SessionImpl(282270616<open>)] after transaction
PROGRAM duration: 1507ms
mvs-migration-shell:>2019-08-15 15:02:40.389 WARN 3939 --- [lTaskExecutor-2] org.jline : Unable to create a system terminal, creating a dumb terminal (enable debug logging for more information)
2019-08-15 15:02:40.389 WARN 3939 --- [lTaskExecutor-1] org.jline : Unable to create a system terminal, creating a dumb terminal (enable debug logging for more information)
Progress MVSThreadPoolTaskExecutor-2 0% │ │ 0/1000 (0:00:00 / ?)
2019-08-15 15:02:41.820 DEBUG 3939 --- [lTaskExecutor-2] o.s.orm.jpa.JpaTransactionManager : Initiating transaction commit
2019-08-15 15:02:41.821 DEBUG 3939 --- [lTaskExecutor-2] o.s.orm.jpa.JpaTransactionManager : Committing JPA transaction on EntityManager [SessionImpl(346995150<open>)]
2019-08-15 15:02:41.825 DEBUG 3939 --- [lTaskExecutor-2] o.s.orm.jpa.JpaTransactionManager : Closing JPA EntityManager [SessionImpl(346995150<open>)] after transaction
Progress MVSThreadPoolTaskExecutor-1 100% │██████████│ 1000/1000 (0:00:08 / 0:
2019-08-15 15:02:49.084 DEBUG 3939 --- [lTaskExecutor-1] o.s.orm.jpa.JpaTransactionManager : Initiating transaction commit
2019-08-15 15:02:49.085 DEBUG 3939 --- [lTaskExecutor-1] o.s.orm.jpa.JpaTransactionManager : Committing JPA transaction on EntityManager [SessionImpl(1848267920<open>)]
2019-08-15 15:02:49.585 DEBUG 3939 --- [lTaskExecutor-1] o.s.orm.jpa.JpaTransactionManager : Closing JPA EntityManager [SessionImpl(1848267920<open>)] after transaction
2019-08-15 15:03:02.981 DEBUG 3939 --- [l-1 housekeeper] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Pool stats (total=10, active=0, idle=10, waiting=0)
2019-08-15 15:03:32.984 DEBUG 3939 --- [l-1 housekeeper] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Pool stats (total=10, active=0, idle=10, waiting=0)
2019-08-15 15:04:02.989 DEBUG 3939 --- [l-1 housekeeper] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Pool stats (total=10, active=0, idle=10, waiting=0)
2019-08-15 15:04:32.995 DEBUG 3939 --- [l-1 housekeeper] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Pool stats (total=10, active=0, idle=10, waiting=0)
I found out where the problem is, in the mentioned method processMigration() there is the method streamAllInInterval(from, to), which returns the data in specified interval. It contains native SQL query:
Select f.* from someView f left join someTable em on em.id = f.utvar where em.id is null AND ROWNUM BETWEEN :from AND :to
This query returns data when I set from 0 and to 500000 but not for 500000 and 1000000. So I rewrote the query with the first mentioned answer in here SQL ROWNUM how to return rows between a specific range and now everything is working.

HibernateTransactionManager rollback transaction

Im trying to update an entity
#Test
#Transactional
public void test(){
ChatState chatState = chatStateDAO.read(1L);
chatState.setState(2);
chatStateDAO.update(chatState);
chatState.setState(2);
}
update method is calling hibernate session's update(). Here's what I have in my log
2016-07-03 17:36:28 TRACE SessionImpl:219 - Opened session at timestamp: 14675565886
2016-07-03 17:36:28 TRACE SessionImpl:1493 - Setting flush mode to: ALWAYS
2016-07-03 17:36:28 TRACE DefaultSaveOrUpdateEventListener:210 - Updating detached instance
2016-07-03 17:36:28 TRACE DefaultSaveOrUpdateEventListener:275 - Updating [ru.jeak.telegram.model.ChatState#1]
2016-07-03 17:36:28 TRACE DefaultSaveOrUpdateEventListener:322 - Updating [ru.jeak.telegram.model.ChatState#1]
2016-07-03 17:36:28 TRACE MyHibernateTransactionManager:943 - Triggering beforeCompletion synchronization
2016-07-03 17:36:28 DEBUG MyHibernateTransactionManager:851 - Initiating transaction rollback
2016-07-03 17:36:28 DEBUG MyHibernateTransactionManager:597 - Rolling back Hibernate transaction on Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])]
2016-07-03 17:36:28 DEBUG TransactionImpl:86 - rolling back
2016-07-03 17:36:28 TRACE AbstractLogicalConnectionImplementor:114 - Preparing to rollback transaction via JDBC Connection.rollback()
2016-07-03 17:36:28 TRACE AbstractLogicalConnectionImplementor:117 - Transaction rolled-back via JDBC Connection.rollback()
2016-07-03 17:36:28 TRACE AbstractLogicalConnectionImplementor:54 - LogicalConnection#afterTransaction
2016-07-03 17:36:28 TRACE ResourceRegistryStandardImpl:286 - Releasing JDBC resources
MyHibernateTransactionManager is default HibernateTransactionManager. I dont understand why this transaction gets rolled back without any error message or something?
You don't need to call update() to make the changes persistent. Changes to a managed entity are saved automatically. And update() is used to attach a detached entity to the session. Your entity is attached.
Regarding the rollback, Spring tests automatically rollback at the end of the test, unless you tell Spring not to do it.

Thread lock after opening new EntityManager

I have a very weird error working with Spring JPA transactions. The thread is locked around 16 minutes and then continues without any problem.
Here is the situation:
#Transactional(propagation = Propagation.REQUIRES_NEW)
public class A {
public String encrypt(String str){
LOG.debug("encrypting...");
// just data base read operations
}
public String encrypt(String str, String str2){
// read and write database operations.
}
public String foo(...){
// read and write database operations.
}
public String bar(...){
// read and write database operations.
}
}
#Transactional(propagation = Propagation.REQUIRES_NEW)
public class B {
public String doSomething(...){
LOG.debug("calling encrypt method...");
String chain1 = this.a.encrypt("whatever");
LOG.debug("calling encrypt method...");
String chain2 = this.a.encrypt("again");
LOG.debug("calling encrypt method...");
String chain3 = this.a.encrypt("and again");
...
}
}
Taking a look to the log file I see that it takes 16 minutes from log "calling encrypt method" to "encripting". So, have activated JTA logs and this is what I see:
15:09:04.317 DEBUG e.i.n.p.d.TipoMensajeDaoDelegate [45] - obteniendo mensaje para tipo operacion 0104 y protocolo 03
15:09:04.318 DEBUG o.s.orm.jpa.JpaTransactionManager [332] - Found thread-bound EntityManager [org.hibernate.ejb.EntityManagerImpl#4e6b01e9] for JPA transaction
15:09:04.319 DEBUG o.s.orm.jpa.JpaTransactionManager [471] - Participating in existing transaction
15:09:04.320 DEBUG o.s.orm.jpa.JpaTransactionManager [332] - Found thread-bound EntityManager [org.hibernate.ejb.EntityManagerImpl#4e6b01e9] for JPA transaction
15:09:04.321 DEBUG o.s.orm.jpa.JpaTransactionManager [471] - Participating in existing transaction
15:09:04.324 DEBUG e.i.n.c.p.p.b.B [485] - calling encrypt method...
15:09:04.325 DEBUG o.s.orm.jpa.JpaTransactionManager [332] - Found thread-bound EntityManager [org.hibernate.ejb.EntityManagerImpl#4e6b01e9] for JPA transaction
15:09:04.326 DEBUG o.s.orm.jpa.JpaTransactionManager [416] - Suspending current transaction, creating new transaction with name [es.indra.nnp.gestorclaves.GestorClavesServiceImpl.cifrar]
15:09:04.326 DEBUG o.s.orm.jpa.JpaTransactionManager [369] - Opened new EntityManager [org.hibernate.ejb.EntityManagerImpl#27f2b012] for JPA transaction
...
15:24:29.954 DEBUG o.s.orm.jpa.JpaTransactionManager [408] - Not exposing JPA transaction [org.hibernate.ejb.EntityManagerImpl#27f2b012] as JDBC transaction because JpaDialect [org.springframework.orm.jpa.DefaultJpaDialect#4d832b01] does not support JDBC Connection retrieval
15:24:29.955 DEBUG e.i.n.g.A [146] - encrypting
15:24:29.956 DEBUG o.s.orm.jpa.JpaTransactionManager [332] - Found thread-bound EntityManager [org.hibernate.ejb.EntityManagerImpl#27f2b012] for JPA transaction
15:24:29.957 DEBUG o.s.orm.jpa.JpaTransactionManager [471] - Participating in existing transaction
15:24:29.958 DEBUG o.s.orm.jpa.JpaTransactionManager [332] - Found thread-bound EntityManager [org.hibernate.ejb.EntityManagerImpl#27f2b012] for JPA transaction
15:24:29.958 DEBUG o.s.orm.jpa.JpaTransactionManager [471] - Participating in existing transaction
15:24:29.962 DEBUG o.s.orm.jpa.JpaTransactionManager [332] - Found thread-bound EntityManager [org.hibernate.ejb.EntityManagerImpl#27f2b012] for JPA transaction
15:24:29.962 DEBUG o.s.orm.jpa.JpaTransactionManager [471] - Participating in existing transaction
...
Here, the facts:
Error does not happen always, but when it does it is always in the same point.
After 16 minutes more or less, the thread continues and calls the same method few times with no problem and finish correctly.
When it happens, it is always around 15 minutes and 30 seconds.
It happens with no concurrency. Anyway, when a thread is locked, if I start another thread there is no problem. The second thread is processed while the first is still locked.
DDBB has being checked looking for database locks while the lock was happening. No database locks were found.
Others methods form class A are called from others points of the code with no problem.
Just happens on production environment. You can imagine how difficult is to do changes.
Database connection is done via JNDI to MySql and application run in Tomcat.
I know that with this information is difficult to find out where the problem is. Just I hope someone can contribute with some thoughts that help me to find what is happening.
For me this sounds pretty much like this SO question.
Using REQUIRES_NEW will always ensure a new Transaction, so if there is an already existing one that should be suspended.
But since nested transactions are not supported by the JPATransactionManager:
On JDBC 3.0, this transaction manager supports nested transactions via
JDBC 3.0 Savepoints. The
AbstractPlatformTransactionManager.setNestedTransactionAllowed(boolean)
"nestedTransactionAllowed"} flag defaults to "false", though, as
nested transactions will just apply to the JDBC Connection, not to the
JPA EntityManager and its cached objects. You can manually set the
flag to "true" if you want to use nested transactions for JDBC access
code which participates in JPA transactions (provided that your JDBC
driver supports Savepoints). Note that JPA itself does not support
nested transactions! Hence, do not expect JPA access code to
semantically participate in a nested transaction.
So the two transactions will share the same JDBC connection and there might be some locking involved. Is it that the transaction timeout is set to 15 minutes and that's why you see it hanging around for this amount of time?

Hibernate does not generate table with annotations

I'm using Wicket in combination with Spring and Hibernate, at least that's what I'm trying to do, the problem comes with auto generating the tables with Hibernate annotations.
I've been trying many changes in the configuration but can't seem to figure out why my configuration doesn't generate any tables. And I'm hoping someone can point me in the right direction, even about the Spring configuration I'm not sure.
I've included all the files I'm using to try to make this work in links, so that it won't be a very long list of configuration files.
I'm using the following class with annotations, http://schrealex.com/downloads/User.java:
#Entity
#Table(name="user")
public class User {
#Id
#Column(name="user_id", unique=true, nullable=false)
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
#Column(name="username")
private String username;
#Column(name="password")
private String password;
#Column(name="firstname")
private String firstname;
#Column(name="lastname")
private String lastname;
#Column(name="birthDate")
private Date birthDate;
#Column(name="email")
private String email;
#Column(name="profile_image")
private String profile_image;
public User() {
}
public User(String username, String password, String email) {
this.username = username;
this.password = password;
this.email = email;
}
// Getter and Setter methods
}
I'm using the following dependencies described in my pom.xml:
http://schrealex.com/downloads/pom.xml
I'm using the following configuration in applicationContext.xml and properties:
http://schrealex.com/downloads/application.properties
http://schrealex.com/downloads/applicationContext.xml
And finally web.xml:
http://schrealex.com/downloads/web.xml
If I'm missing any files you'd like to see, just ask.
Edit :-
Added start up logging:
SSL access to the quickstart has been enabled on port 8443
You can access the application using SSL on https://localhost:8443
>>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP
INFO - Server - jetty-7.6.3.v20120416
INFO - tandardDescriptorProcessor - NO JSP Support for /, did not find org.apache.jasper.servlet.JspServlet
INFO - / - Initializing Spring root WebApplicationContext
INFO - ContextLoader - Root WebApplicationContext: initialization started
INFO - XmlWebApplicationContext - Refreshing org.springframework.web.context.support.XmlWebApplicationContext#1c35ce99: display name [Root WebApplicationContext]; startup date [Wed Nov 28 19:53:33 CET 2012]; root of context hierarchy
INFO - XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [applicationContext.xml]
INFO - XmlWebApplicationContext - Bean factory for application context [org.springframework.web.context.support.XmlWebApplicationContext#1c35ce99]: org.springframework.beans.factory.support.DefaultListableBeanFactory#2a9b5441
INFO - pertyPlaceholderConfigurer - Loading properties file from URL [file:/C:/Users/CE_REAL/Documents/Development/media-database/target/classes/application.properties]
INFO - DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#2a9b5441: defining beans [wicketApplication,placeholderConfigurer,dataSource,transactionManager,transactionInterceptor,managerTemplate,sessionFactory]; root of factory hierarchy
INFO - Version - Hibernate Annotations 3.4.0.GA
INFO - Environment - Hibernate 3.2.6
INFO - Environment - hibernate.properties not found
INFO - Environment - Bytecode provider name : cglib
INFO - Environment - using JDK 1.4 java.sql.Timestamp handling
INFO - Version - Hibernate Commons Annotations 3.1.0.GA
INFO - AnnotationConfiguration - Hibernate Validator not found: ignoring
INFO - notationSessionFactoryBean - Building new Hibernate SessionFactory
INFO - earchEventListenerRegister - Unable to find org.hibernate.search.event.FullTextIndexEventListener on the classpath. Hibernate Search is not enabled.
INFO - ConnectionProviderFactory - Initializing connection provider: org.springframework.orm.hibernate3.LocalDataSourceConnectionProvider
INFO - SettingsFactory - RDBMS: MySQL, version: 5.5.16-log
INFO - SettingsFactory - JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-5.1.21 ( Revision: ${bzr.revision-id} )
INFO - Dialect - Using dialect: org.hibernate.dialect.MySQLDialect
INFO - TransactionFactoryFactory - Transaction strategy: org.springframework.orm.hibernate3.SpringTransactionFactory
INFO - actionManagerLookupFactory - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
INFO - SettingsFactory - Automatic flush during beforeCompletion(): disabled
INFO - SettingsFactory - Automatic session close at end of transaction: disabled
INFO - SettingsFactory - JDBC batch size: 15
INFO - SettingsFactory - JDBC batch updates for versioned data: disabled
INFO - SettingsFactory - Scrollable result sets: enabled
INFO - SettingsFactory - JDBC3 getGeneratedKeys(): enabled
INFO - SettingsFactory - Connection release mode: auto
INFO - SettingsFactory - Maximum outer join fetch depth: 2
INFO - SettingsFactory - Default batch fetch size: 1
INFO - SettingsFactory - Generate SQL with comments: disabled
INFO - SettingsFactory - Order SQL updates by primary key: disabled
INFO - SettingsFactory - Order SQL inserts for batching: disabled
INFO - SettingsFactory - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
INFO - ASTQueryTranslatorFactory - Using ASTQueryTranslatorFactory
INFO - SettingsFactory - Query language substitutions: {}
INFO - SettingsFactory - JPA-QL strict compliance: disabled
INFO - SettingsFactory - Second-level cache: enabled
INFO - SettingsFactory - Query cache: disabled
INFO - SettingsFactory - Cache provider: org.hibernate.cache.EhCacheProvider
INFO - SettingsFactory - Optimize cache for minimal puts: disabled
INFO - SettingsFactory - Structured second-level cache entries: disabled
INFO - SettingsFactory - Echoing all SQL to stdout
INFO - SettingsFactory - Statistics: disabled
INFO - SettingsFactory - Deleted entity synthetic identifier rollback: disabled
INFO - SettingsFactory - Default entity-mode: pojo
INFO - SettingsFactory - Named query checking : enabled
INFO - SessionFactoryImpl - building session factory
WARN - ConfigurationFactory - No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: jar:file:/C:/Users/CE_REAL/.m2/repository/net/sf/ehcache/ehcache/1.2.3/ehcache-1.2.3.jar!/ehcache-failsafe.xml
INFO - essionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured
INFO - SchemaExport - Running hbm2ddl schema export
INFO - SchemaExport - exporting generated schema to database
INFO - SchemaExport - schema export complete
INFO - ContextLoader - Root WebApplicationContext: initialization completed in 671 ms
INFO - ContextHandler - started o.e.j.w.WebAppContext{/,file:/C:/Users/CE_REAL/Documents/Development/media-database/src/main/webapp/},src/main/webapp
WARN - WebXmlFile - web.xml: No url-pattern found for 'filter' with name 'wicket-spring-hibernate'
INFO - WebXmlFile - web.xml: url mapping found for filter with name wicket-spring-hibernate:
WARN - WicketFilter - Unable to determine filter path from filter init-param, web.xml, or servlet 3.0 annotations. Assuming user will set filter path manually by calling setFilterPath(String)
INFO - Application - [wicket-spring-hibernate] init: Wicket core library initializer
INFO - RequestListenerInterface - registered listener interface [RequestListenerInterface name=IBehaviorListener, method=public abstract void org.apache.wicket.behavior.IBehaviorListener.onRequest()]
INFO - RequestListenerInterface - registered listener interface [RequestListenerInterface name=IFormSubmitListener, method=public abstract void org.apache.wicket.markup.html.form.IFormSubmitListener.onFormSubmitted()]
INFO - RequestListenerInterface - registered listener interface [RequestListenerInterface name=ILinkListener, method=public abstract void org.apache.wicket.markup.html.link.ILinkListener.onLinkClicked()]
INFO - RequestListenerInterface - registered listener interface [RequestListenerInterface name=IOnChangeListener, method=public abstract void org.apache.wicket.markup.html.form.IOnChangeListener.onSelectionChanged()]
INFO - RequestListenerInterface - registered listener interface [RequestListenerInterface name=IRedirectListener, method=public abstract void org.apache.wicket.IRedirectListener.onRedirect()]
INFO - RequestListenerInterface - registered listener interface [RequestListenerInterface name=IResourceListener, method=public abstract void org.apache.wicket.IResourceListener.onResourceRequested()]
INFO - Application - [wicket-spring-hibernate] init: Wicket extensions initializer
INFO - WebApplication - [wicket-spring-hibernate] Started Wicket version 6.2.0 in DEVELOPMENT mode
********************************************************************
*** WARNING: Wicket is running in DEVELOPMENT mode. ***
*** ^^^^^^^^^^^ ***
*** Do NOT deploy to your live server(s) without changing this. ***
*** See Application#getConfigurationType() for more information. ***
********************************************************************
INFO - WebXmlFile - web.xml: url mapping found for filter with name wicket.media-database: [/login/*]
INFO - Application - [wicket.media-database] init: Wicket core library initializer
INFO - Application - [wicket.media-database] init: Wicket extensions initializer
INFO - WebApplication - [wicket.media-database] Started Wicket version 6.2.0 in DEVELOPMENT mode
********************************************************************
*** WARNING: Wicket is running in DEVELOPMENT mode. ***
*** ^^^^^^^^^^^ ***
*** Do NOT deploy to your live server(s) without changing this. ***
*** See Application#getConfigurationType() for more information. ***
********************************************************************
INFO - AbstractConnector - Started SocketConnector#0.0.0.0:8080
INFO - SslContextFactory - Enabled Protocols [SSLv2Hello, SSLv3, TLSv1, TLSv1.1, TLSv1.2] of [SSLv2Hello, SSLv3, TLSv1, TLSv1.1, TLSv1.2]
INFO - AbstractConnector - Started SslSocketConnector#0.0.0.0:8443
Edit :-
I tried renaming my User class to MediaUser and the #Table annotation to mediaUser to avoid problems with the USER word being reserved for some databases.
What I've found from the start up logging, as seen above, is that it does say it's running the export:
INFO - SchemaExport - Running hbm2ddl schema export
INFO - SchemaExport - exporting generated schema to database
INFO - SchemaExport - schema export complete
Also tried different approaches to the Hibernate annotations, like using other imports, #Table is now used by importing javax.persistence.Table, but I also tried the Hibernate org.hibernate.annotations.table, thus far without a solution to my problem.
I've found the answer to my problem, the annotations need either be set on the instance variables or on the class and it's methods and it needs to implement Serializable like:
#Entity
public class User implements Serializable {
#Id
#GeneratedValue
private Long id;
private String username;
private String password;
private String firstname;
private String lastname;
private Date birthDate;
private String email;
private String profileImage;
public User() {
}
public User(String username, String password, String email) {
this.username = username;
this.password = password;
this.email = email;
}
// Getter and Setter methods
#Column
public getUsername() {
return username;
}
#Column
public getPassword() {
return password;
}
#Column
public getFirstname() {
return firstname;
}
#Column
public getLastname() {
return lastname;
}
#Column
#Temporal(TemporalType.TIME)
public getBirthDate() {
return birthDate;
}
#Column
public getEmail() {
return email;
}
#Column
public getProfileImage() {
return profileImage;
}
}
I had the same problem ... in my case, the problem was because the USER word is reserved for some data bases.
So, considering that your hibernate configuration files are right, just add a prefix in all your tables and the problem was solved.
I hope this solve your problem too =)
Try to use
#EntityScan({" yourentitypackagehere "})
in your springboot application

Categories