Spring:Propagation.REQUIRED not working - java

I am inserting records in a couple of tables namely Dept and Emp. If the Dept table is successfully created then only I want to insert records in Emp table. Also, if any of the insert in Emp fails, then I want to rollback all the transaction which includes both rollback from Emp as well as Dept tables.
I tried this using Propagation.REQUIRED as shown below:
Java File
public void saveEmployee(Employee empl){
try {
jdbcTemplate.update("INSERT INTO EMP VALUES(?,?,?,?,?)",empl.getEmpId(),empl.getEmpName(),
empl.getDeptId(),empl.getAge(),empl.getSex());
} catch (DataAccessException e) {
e.printStackTrace();
}
}
#Transactional(propagation=Propagation.REQUIRED)
public void saveRecords(){
saveDepartment(dept);
saveEmployee(empl);
}
context.xml
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
Problem:
Even if an insertion in Emp table fails, the Dept insertion is getting persisted which I don't want. I want to rollback everything.
Please suggest.

The problem is your catch block. Since the exception is catched the tx don't rollback.
You must throw the exception :
public void saveEmployee(Employee empl){
try {
jdbcTemplate.update("INSERT INTO EMP VALUES(?,?,?,?,?)",empl.getEmpId(),empl.getEmpName(),
empl.getDeptId(),empl.getAge(),empl.getSex());
} catch (DataAccessException e) {
e.printStackTrace();
throw e;
}
}
And by the way, the semantic of Progation.Required just means : create a new tx if it don't exists OR use an existing one if there is tx running.
Following your comment here is a suggestion to see the effect of NEW tx :
#Transactional(propagation=Propagation.REQUIRES_NEW)
public void saveEmployee(Employee empl){
try {
jdbcTemplate.update("INSERT INTO EMP VALUES(?,?,?,?,?)",empl.getEmpId(),empl.getEmpName(),
empl.getDeptId(),empl.getAge(),empl.getSex());
} catch (DataAccessException e) {
e.printStackTrace();
throw e;
}
}
#Transactional(propagation=Propagation.REQUIRED)
public void saveRecords(){
saveDepartment(dept);
try{
saveEmployee(empl);
}catch(Exception e){Logger.log("Fail to save emp !");}
}
The key point to see the effect of REQUIRES_NEW is to catch the exception around saveEmployee. If you don't catch it : the exception will propagate in the other tx (the one started when entering saveRecords() ) and it will rollback too.

Related

Spring, catch exception

I have small problem. I can't catch exception in method. I need to catch ConstraintViolationException to process it. Somebody know why it happens?
#Transactional(rollbackFor = Exception.class)
public void saveCustomer(Customer customer) {
Session session = sessionFactory.getCurrentSession();
try {
session.save(customer);
} catch (Throwable e) {
log.debug(e);
// Process exception
}
}
I ran into similar problem some days ago.
I looked at the StackTrace and used PersistenceException.
Try it:
#Transactional(rollbackFor = Exception.class)
public void saveCustomer(Customer customer) {
Session session = sessionFactory.getCurrentSession();
try {
session.save(customer);
} catch (PersistenceException e) {
log.debug(e);
// Process exception
}
}
Based on question, it looks like session.save(..) is not throwing exception at all but rather persisting entity into db. Can you check if your customer object got saved into db after this method got executed.
You might be looking for unique key constraint violation or some sort but session.save(..) is saving entity into db. You might need to check your how you have defined your Customer entity as well.

Spring #transactional with hibernate issue - not valid without an active transaction

Preamble - using Spring
I am confused as to the purpose of the spring #Transactional annotation. I thought from a few blog posts I've read that it would allow me to simplify transaction management and just write this, and it would handle connection/commit/rollback automagically:
public class DaoImpl implements Dao {
#Autowired
private SessionFactory sessionFactory;
#Transactional
public void saveOrUpdateOne(final AdditionalDataItem item) {
Session session = sessionFactory.getCurrentSession();
session.saveOrUpdate(p_item);
}
}
However this gives me an exception: " Calling method 'saveOrUpdate' is not valid without an active transaction"
If I instead change the save method to this, it all works - so my question is, what is #Transactional doing?
#Override
#Transactional
public void saveOrUpdateOne(final AdditionalDataItem p_item) {
Session session = null;
Transaction trans = null;
try {
session = sessionFactory.getCurrentSession();
trans = session.beginTransaction();
TransactionStatus status = trans.getStatus();
session.saveOrUpdate(p_item);
trans.commit();
} catch (Exception e) {
LOGGER.error("Exception saving data: {}", e.getMessage());
if (trans != null) {
try {
trans.rollback();
} catch (RuntimeException rbe) {
LOGGER.error("Couldn’t roll back transaction", rbe);
}
}
} finally {
if (session != null && session.isOpen()) {
try {
session.close();
} catch (HibernateException ne) {
LOGGER.error("Couldn’t close session", ne);
}
}
}
}
For reference, I'm using Java 11 with Spring Framework 5.3.7 and hibernate 5.5.7 and have appropriate dao, session factory and tx manager beans:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="${sessionFactory.datasource}" />
<property name="configLocation" value="${sessionFactory.configLocation}" />
</bean>
<bean id="txManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="Dao" class="com.xxxxx.dao.DaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
It is because you do not enable #Transactional yet and also not begin the transaction when calling session.saveOrUpdate(), so it gives you the error 'not valid without an active transaction' .
To enable #Transactional, you have to use #EnableTransactionManagement or add <tx:annotation-driven/> in case you are using XML configuration . It basically does the following for you (source) :
#EnableTransactionManagement and <tx:annotation-driven/> are
responsible for registering the necessary Spring components that power
annotation-driven transaction management, such as the
TransactionInterceptor and the proxy- or AspectJ-based advice that
weaves the interceptor into the call stack when JdbcFooRepository's
#Transactional methods are invoked.
Your working example works because you manually manage the transaction by yourself .It is nothing to do with #Transactional since you never enable it.
Take the working codes as an example , what #Transactional does for you is that you no longer need to manually write the following transaction codes as all of them will be encapsulated in the TransactionInterceptor and execute around your #Transactional method based on AOP :
public Object invoke() {
Session session = null;
Transaction trans = null;
try {
session = sessionFactory.getCurrentSession();
trans = session.beginTransaction();
TransactionStatus status = trans.getStatus();
/***********************************************/
Here it will invoke your #Transactional Method
/************************************************/
trans.commit();
} catch (Exception e) {
LOGGER.error("Exception saving data: {}", e.getMessage());
if (trans != null) {
try {
trans.rollback();
} catch (RuntimeException rbe) {
LOGGER.error("Couldn’t roll back transaction", rbe);
}
}
} finally {
if (session != null && session.isOpen()) {
try {
session.close();
} catch (HibernateException ne) {
LOGGER.error("Couldn’t close session", ne);
}
}
}
}
So you can see that your #Transactional method will become very clean after removing these "ceremony" codes.
#Transactional is used if you want to update 2 tables if one of them failed the other one will rollback automatic
you can use it above method
and you can call save or update using bean of a Repository class

Spring Jdbc template setAutocommit(false)

I want insert multiple rows in db table.
I am using SpringJdbc.
How can i manage transaction in SpringJdbc connection.
My code is:
#Override
#Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
public int addUserRelationshipMapping(final ArrayList<UserDO> userDOs, final long userId) throws UserDataException {
final JdbcTemplate jd = this.getJdbctemplate();
try {
jd.getDataSource().getConnection().setAutoCommit(false);
} catch (SQLException e) {
e.printStackTrace();
}
int totalAdded = 0;
try {
int[] isAdded = jd.batchUpdate(ADD_USER_RELATION_MAPPING, new BatchPreparedStatementSetter() {
#Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
final long userRelationId = jd.queryForObject(USER_RELATION_KEY, Long.class);
UserDO userDO = userDOs.get(i);
ps.setLong(1, userRelationId);
ps.setLong(2, userId);
ps.setLong(3, userDO.getprimaryUserId());
ps.setInt(4, 1);
ps.setInt(5, 0);
jd.getDataSource().getConnection().commit();
}
#Override
public int getBatchSize() {
return userDOs.size();
}
});
totalAdded = isAdded.length;
} catch (DuplicateKeyException dExp) {
log.info("error for duplicate key exception ",dExp);
log.error(dExp);
} catch (DataAccessException dExp) {
throw new UserDataException("error while adding user relation for userId is" + userId, dExp);
}
return totalAdded;
}
In this code userRelationId return always old values not updated table values.
So will use database connection commit.
SOF question:Java MYSQL/JDBC query is returning stale data from cached Connection
I got error message:
Caused by: java.sql.SQLException: Can't call commit when autocommit=true
So i need help for this.
Advance thanks.
See the example of how to set auto commit false
<bean id="database" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource">
<bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
...
<property name="defaultAutoCommit" value="false" />
...
</bean>
</property>
ref:
spring 3.1: jdbcTemplate auto commit to false.
You can also try the annotation based connection transaction management ?
How can I config to turn off autocommit in Spring + JDBC?

Transaction not successfully started (while tx.commit() is surrounded by a if condition)

First time that I ran into this error I've surrounded my tx.commit() with a if condition but am not sure why I am still receiving this error.
Struts Problem Report
Struts has detected an unhandled exception:
Messages:
Transaction not successfully started
File: org/hibernate/engine/transaction/spi/AbstractTransactionImpl.java
Line number: 200
Stacktraces
org.hibernate.TransactionException: Transaction not successfully started
org.hibernate.engine.transaction.spi.AbstractTransactionImpl.rollback(AbstractTransactionImpl.java:200)
After a product has been selected by user, in my main function I will call two functions as following.
First function to retrieve the object of selected product.
Second function to check if selected user has the product therefore it returns true if client has the product otherwise returns false;
Function 1
....
Product pro = new Product();
final Session session = HibernateUtil.getSession();
try {
final Transaction tx = session.beginTransaction();
try {
pro = (Product) session.get(Product.class, id);
if (!tx.wasCommitted()) {
tx.commit();
}
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
}
} finally {
HibernateUtil.closeSession();
}
.....
Function 2
.....
final Session session = HibernateUtil.getSession();
try {
final Transaction tx = session.beginTransaction();
try {
User user = (User) session.get(User.class, id);
if (!tx.wasCommitted()) {
tx.commit();
}
if(client.hasProduct(proId)){
return client.getProduct(proId);
}
return false;
} catch (Exception e) {
tx.rollback(); <<<Error is on this line
e.printStackTrace();
}
} finally {
HibernateUtil.closeSession();
}
....
Take a look at Transaction.isActive() method. You can wrap call to rollback() method with condition, checking whether transaction is still active. And the second, I'd prefer the following code:
final Session session = HibernateUtil.getSession();
try {
final Transaction tx = session.beginTransaction();
// do things
tx.commit();
} finally {
if (tx.isActive()) {
try {
tx.rollback();
} catch (Exception e) {
logger.log("Error rolling back transaction", e);
}
}
try {
session.close();
} catch (Exception e) {
logger.log("Error closing session", e);
}
}
Of course, code in the finally section better to wrap into public static method and just call it in every finally.
BTW, why are you doing something outside tranaction? I usually commit after all things get done, to achieve a better consistency and avoid LazyInitializationException.
One possibility is that the exception you are catching in the second functions is from the code after the commit(), so you end up trying to rollback a transaction that is already committed, which is not allowed.
You could try reorganizing your code to make sure that rollback is never called after commit. Maybe even something simple like reducing the scope of the inner try-catch:
final Session session = HibernateUtil.getSession();
try {
final Transaction tx = session.beginTransaction();
try {
User user = (User) session.get(User.class, id);
if (!tx.wasCommitted()) {
tx.commit();
}
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
}
if(client.hasProduct(proId)){
return client.getProduct(proId);
}
return false;
} finally {
HibernateUtil.closeSession();
}
The error indicates the transaction wasn't started at the time tried to roll back - and the problem may be that you are trying to wrap a get, which does not alter the db state and does not leave behind garbage that needs to be committed or rolled back. Nothing changes when you perform select *.
In addition to this, you may want to extract this transaction handling into a common method that is independent of the work being done, so you don't have to write this over and over again, that leaves your code open for bugs. Basically, it seems like you are getting DB objects but then intermingling some business logic withing the same method. Perhaps consider doing something like below:
DB Handling Function
public static <T> T getDBObject( Class<T> clazz, Serializable id )
throws SQLException
{
Session session = null;
try
{
session = HibernateUtil.getSession();
return (T)session.get( clazz, id );
}
finally
{
if ( session != null )
{
session.close();
}
}
}
Now that you can pull object of the DB (note that they will be detached, but still valid), you can then perform work on the objects. I many not have captured exactly what you need to check, but it seems like it is something like:
Example Comparison Function
public boolean doesUserHaveProduct(Serializable userId, Serializable productId)
{
try
{
User user = getDBObject(User.class, userId);
Product product = getDBObject( Product.class, productId );
return user.hasProduct( product );
}
catch (SQLException e)
{
e.printStackTrace();
return false;
}
}

EntityManager exception handling in session bean

I have a managed stateless session bean with injected EntityManager em.
What I am trying to do is to have a database table with unique column. Then I run some algorithm which is trying to insert an entity. If entity exists however it will update it or skip it.
I would like to have something like this:
try {
em.persist(cd);
em.flush();
} catch (PersistenceException e) {
// Check if the exception is DatabaseException and ConstraintViolation
// Update instead or skip it
}
Problem is that I am able to catch only PersistenceException. DatabaseException is not catched. It is sad because only DatabaseException has method called getDatabaseErrorCode() I would like to use to check duplicate entry. I dont understand it because PersistenceException.getCause() returns DatabaseException.
So my question is: How do I catch DatabaseException and check the MySQL error code?
Thank you for any ideas and experiences with this.
I have a suggestion which is I use in my application. We can retrieve the SQLException from PersistenceException. After that, try to get sql error code for SQLException. If your requirement is to get the sql error code, your can follow my example;
public void insert(Group group) throws DAOException {
try {
//your operation
em.flush();
logger.debug("insert() method has been successfully finisehd.");
} catch (PersistenceException pe) {
String sqlErroCode = getErrorCode(pe);
// do your operation based on sql errocode
}
}
protected String getErrorCode(RuntimeException e) {
Throwable throwable = e;
while (throwable != null && !(throwable instanceof SQLException)) {
throwable = throwable.getCause();
}
if (throwable instanceof SQLException) {
Properties properties = --> load sql error code form configuration file.
SQLException sqlex = (SQLException) throwable;
String errorCode = properties.getProperty(sqlex.getErrorCode() + "");
return errorCode;
}
return "NONE";
}
Example error code configuration of mysql
mysql_error_code.properties
#MySQL Database
1062=DUPLICATE_KEY_FOUND
1216=CHILD_RECORD_FOUND
1217=PARENT_RECORD_NOT_FOUND
1048=NULL_VALUE_FOUND
1205=RECORD_HAS_BEEN_LOCKED

Categories

Resources