Spring not roll back transaction if exception throws in the application - spring

I developed the application using spring transactions and insert records in the table.
I'm explicitly throwing the exception in DAO class but spring is inserting the record into the table rather than roll back the transaction.
I have created the two applications as below . In Case 1 record is inserted into table even though exception is thrown . But In Case 2 no record is inserted and spring roll back the transaction successfully. Can you explain me the difference between these two applications.
Case 1:
Item.java
public class Item {
int itemNo;
String itemName;
String itemType;
String itemSize;
public int getItemNo() {
return itemNo;
}
public void setItemNo(int itemNo) {
this.itemNo = itemNo;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemType() {
return itemType;
}
public void setItemType(String itemType) {
this.itemType = itemType;
}
public String getItemSize() {
return itemSize;
}
public void setItemSize(String itemSize) {
this.itemSize = itemSize;
}
}
ItemDao
#Service
public class ItemDao {
#Autowired
JdbcTemplate jdbcTemplate ;
void insert(Item item){
jdbcTemplate.update("insert into item_test(itemno, itemtype,itemsize,itemname) values (?,?,?,?)", new Object[]{item.getItemNo(),item.getItemType(),item.getItemSize(),item.getItemName()});
int a=2/0;
}
}
ItemService.java
#Service
public class ItemService {
#Autowired
ItemDao itemDao;
#Transactional
public void insert(Item item){
try{
itemDao.insert(item);
}
catch(Exception e){
e.printStackTrace();
}
}
}
Test.java
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ct = new ClassPathXmlApplicationContext("spring.xml");
ItemService itemService = ct.getBean("itemService", ItemService.class);
Item item = new Item();
item.setItemNo(1234);
item.setItemName("sofa");
item.setItemSize("4");
item.setItemType("furniture");
itemService.insert(item);
}
}
spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- Enable Annotation based Declarative Transaction Management -->
<tx:annotation-driven proxy-target-class="true" transaction-manager="transactionManager" />
<context:component-scan base-package="com.spring.springtransaction" />
<!-- Creating TransactionManager Bean, since JDBC we are creating of type
DataSourceTransactionManager -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- MySQL DB DataSource -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#locahost:1521:xe)))" />
<property name="username" value="system" />
<property name="password" value="system" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="itemService" class="com.spring.springtransaction.ItemService" />
</beans>
Case 2:
ItemService.java
#Service
public class ItemService {
#Autowired
ItemDao itemDao;
#Autowired
ItemManger itemManger;
#Transactional
public void insert(Item item){
try{
itemManger.insert(item);
}
catch(Exception e){
e.printStackTrace();
}
}
}
ItemManger.java
#Service
public class ItemManger {
#Autowired
ItemDao itemDao;
#Transactional
public void insert(Item item){
itemDao.insert(item);
}
}
ItemDao.java
#Service
public class ItemDao {
#Autowired
JdbcTemplate jdbcTemplate ;
void insert(Item item){
jdbcTemplate.update("insert into item_test(itemno, itemtype,itemsize,itemname) values (?,?,?,?)", new Object[]{item.getItemNo(),item.getItemType(),item.getItemSize(),item.getItemName()});
int a=2/0;
}
}

Annotate you ItemDao as #Repository instead of #Service
You should execute unit test with spring Transactional context instead of main , for example using TestNG:
#ContextConfiguration(classes = {ConfigurationClass.class})
#ActiveProfiles({"test"})
public class TestItemDAO extends AbstractTransactionalTestNGSpringContextTests {
#Autowired
private ItemDao dao;
#Test
public void testItemDao() {
dao.insert(item);
}
}

Remove the try block, you are trying to handle the exception so this is reason why RollbackException is not cutting the transaction stream.

Related

Spring :: #Transactional not working

I am new to Spring and learning the transaction concepts. Unable to get the #Transactional to work.
Use Case:
Data insert of Employee and Employee details should rollback when getEmployee() throws RunTimeException. But the rollback is not happening.
I am using Oracle database 11g and spring 4.3.1.RELEASE. Below is the standalone java code am running.
Code
public static void main( String[] args )
{
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("spring-bean.xml");
ctx.registerShutdownHook();
Employee emp = new Employee("149518", "Mickey", "Mouse", "15 years", "tennis");
IEmployee empIntfc = (IEmployee)ctx.getBean("empService");
try {
empIntfc.createEmployee(emp);
empIntfc.createEmployeeDetails(emp);
//Below will throw RunTime Exception
empIntfc.getEmployee(2);
}catch (Exception e ) {
e.printStackTrace();
} finally {
ctx.close();
}
}
EmployeeService.java
public class EmployeeService implements IEmployee {
private DataSource dataSource;
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
jdbcTemplate = new JdbcTemplate(this.dataSource);
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
#Override
#Transactional
public int createEmployee(Employee emp) {
String sql1 = "INSERT INTO TEST_T1(EMP_ID, EMP_FNAME, EMP_LNAME) values
(?,?,?)";
return getJdbcTemplate().update(sql1, emp.getEmpId(),
emp.getEmpFirstName(), emp.getEmpLastName());
}
#Override
#Transactional
public int createEmployeeDetails(Employee emp) {
String sql = "INSERT INTO TEST_T2(EMP_ID, EXP, SKILLS) values (?,?,?)";
return getJdbcTemplate().update(sql, emp.getEmpId(), emp.getExp(),
emp.getSkills());
}
#Override
#Transactional(readOnly = true, noRollbackFor=RuntimeException.class)
public Employee getEmployee(int empId) {
throw new RuntimeException("Intentional runtime exception");
}
}
spring-bean.xml
<beans xmlns="http://www.springframework.org/schema/beans">
<context:annotation-config/>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:#//xxxx:1521/xxxx"/>
<property name="username" value="user"/>
<property name="password" value="user"/>
</bean>
<bean id="empService" class="com.service.EmployeeService">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
Your main method is not transactional ... means : entering 'createEmployee' creates a new transaction and commits it, 'createEmployeeDetails' creates a new transaction and commits it .

#Autowired annotation in spring

i am relatively new in spring and i have problems with understanding fundamentals of spring mvc..
My controller
#Controller
public class HomeController {
private ContactManager contactManager;
#Autowired
public void setContactManager(ContactManager contactManager) {
this.contactManager = contactManager;
}
#RequestMapping(value="/")
public ModelAndView listContact(ModelAndView model) throws IOException {
List<Contact> listContact = contactManager.list();
model.addObject("listContact", listContact);
model.setViewName("home");
return model;
}
...
Contact ManagerImpl, and implementation of interface method
public class ContactManagerImpl implements ContactManager {
private DataSource dataSource;
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
...
ContactManager
public interface ContactManager {
public void saveOrUpdate(Contact contact);
public void delete(int contactId);
public Contact get(int contactId);
public List<Contact> list();
}
And root-context.xml
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="sec"/>
</bean>
<bean id="managmentService" class="spring.contact.impl.model.ContactManagerImpl">
<property name="dataSource" ref="dataSource"/>
</bean>
My problem is that i get error:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of
type [spring.contact.api.ContactManager] found for dependency: expected at least 1
bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
And of course the problem is with #Autowired annotations. How can i fix it ? When i removed #Autowired annotations i get another error: NullPointerException (manager in HomeController).
Your Controller should be..
#Controller
public class HomeController {
#Autowired
#Qualifier("managmentService")
private ContactManager contactManager;
#RequestMapping(value="/")
public ModelAndView listContact(ModelAndView model) throws IOException {
List<Contact> listContact = contactManager.list();
model.addObject("listContact", listContact);
model.setViewName("home");
return model;
}
...
In your configuration add also <context:annotation-config />that is used in order to be able to use #Autowired annotation.
An example of <context:annotation-config />
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<!-- bean definitions go here -->
</beans>
Move the #Autowired annotation to the declaration for ContactManager.
You won't need the setter, delete it.

Getting the entity manager

i'm using spring data jpa but i want execute some costume query so how can i get the entity manager in my java classes to make entityManager.createQuery(..)
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="persistenceYous" />
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="persistence" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
</bean>
You can obtain your EntityManager as in any other spring application:
public class ProductDaoImpl implements ProductDao {
private EntityManager em;
#PersistenceContext
public void setEntityManager(EntityManager em) {
this.em = em;
}
public Collection loadProductsByCategory(String category) {
em. ....
....
}
}
See: http://docs.spring.io/spring/docs/4.0.0.RELEASE/spring-framework-reference/html/orm.html#orm-jpa-straight
In your applicationContext.xml, check that you have the following:
<context:annotation-config />
That will add support for several annotations, such as #PersistenceContext, that injects an EntityManager. So in your Spring-managed beans, you can do:
public class MyClass {
private EntityManager entityManager;
#PersistenceContext
public void setEntityManager(EntityManager em) {
this.entityManager = em
}
public void myMethod() {
Query q = entityManager.createQuery(...);
// ...
}
}
If you want to add suport for just #PersistenceContext, and not the other annotations that <context:annotation-config /> supports, you would delete that from the applicationContext.xml and add the specific BeanPostProcessor:
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" scope="singleton">
<!-- Optional configuration of PersistenceAnnotationBeanPostProcessor, for advanced use cases -->
</bean>
Firstly follow this link to get the steps required to implement..
check this link
In second step he uses #Autowired private JdbcOperations operations;
But that doesn't work for me, so i used the following code.. Which worked for me.
#Component
public class MayorRepositoryImpl extends JdbcDaoSupport implements MayorRepositoryCustom {
#Override
public List<Employee> getUsers(String role) {
return getJdbcTemplate().query("Write your custom query",new RowMapper<Employee>(){
#Override
public Employee mapRow(ResultSet rs, int rownumber) throws SQLException {
// Mapping each row and adding to list and returning the list
Employee employeeBean=new Employee();
employeeBean.setId(rs.getInt("id"));
employeeBean.setEmployeeNumber(rs.getString("employeeNumber"));
employeeBean.setName(rs.getString("name"));
employeeBean.setWorkEmailAddress(rs.getString("workEmailAddress"));
employeeBean.setPersonalEmailAddress(rs.getString("personalEmailAddress"));
return employeeBean;
}
});
}
}
This is perfectly working for me..
If you find any difficulty let me know to help you.
Cheers

UsernameTokenValidator Can not #Autowired Dao

I have a Spring-ws and i am using Apahce-wss4j for spring-ws authentication. I want to use my Dao class in my custom TokenValidator class. But there was an exception can not #Autowired my Dao class. Here is my code
applicationContext.xml
<bean id="myWssConfig" class="tr.com.xxx.services.MyWssConfig"/>
<bean id="kepDBDAO" class="tr.com.xxx.dao.KepDBDAOImpl"/>
<bean id="ssha" class="tr.com.xxx.utils.SSHA"/>
<bean id="memberStatusService" class="tr.com.xxx.services.MemberStatusServiceImpl"/>
<bean id="myUsernameTokenValidator" class="tr.com.xxx.services.MyUsernameTokenValidator">
<property name="kepDBDAO" ref="kepDBDAO"/>
</bean>
<sws:interceptors>
<bean class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="validationActions" value="UsernameToken"/>
<property name="validationCallbackHandler" ref="callbackHandler"/>
<property name="wssConfig">
<ref bean="myWssConfig"/>
</property>
</bean>
</sws:interceptors>
Here is MyWssConfig.java
#Component("myWssConfig")
public class MyWssConfig extends WSSConfig {
public MyWssConfig() {
setValidator(WSSecurityEngine.USERNAME_TOKEN, MyUsernameTokenValidator.class);
setRequiredPasswordType(WSConstants.PASSWORD_TEXT);
}
}
And here is MyUsernameTokenValidator.java
#Component
public class MyUsernameTokenValidator extends UsernameTokenValidator {
private static final Logger LOGGER = LoggerFactory
.getLogger(MyUsernameTokenValidator.class);
#Autowired
private KepDBDAO kepDBDAO;
#Transactional
protected void verifyPlaintextPassword(UsernameToken usernameToken, RequestData data) throws WSSecurityException {
if (usernameToken != null && usernameToken.getPassword() != null) {
byte[] saltValue = null;
kepDBDAO.getWsUsers("basvuru");
String hashPassword = null;
try {
hashPassword = SSHA.calculateSSHA256(saltValue, usernameToken.getPassword());
} catch (NoSuchAlgorithmException e) {
LOGGER.error(e.toString(), e);
} catch (IOException e) {
LOGGER.error(e.toString(), e);
}
usernameToken.setPassword(hashPassword);
super.verifyDigestPassword(usernameToken, data);
}
}
public KepDBDAO getKepDBDAO() {
return kepDBDAO;
}
public void setKepDBDAO(KepDBDAO kepDBDAO) {
this.kepDBDAO = kepDBDAO;
}
}
Couldn't #Autowired my KepDBDAO when I call webservice in SOAPUI.
Help me please.. THank you all guys.
Try this:
1. In applicationContext:
<context:component-scan base-package="tr.com.xxx.dao"/>
<context:component-scan base-package="package for MyUsernameTokenValidator"/>
remove these beans:
kepDBDAO, myUsernameTokenValidator
2. Remove setter and getter for KepDBDAO in MyUsernameTokenValidator
3. Make sure KepDBDAOImpl is marked as #Service
I solved my problem.
#Component("myWssConfig")
public class MyWssConfig extends WSSConfig {
#Autowired
private MyUsernameTokenValidator myUsernameTokenValidator;
//
#PostConstruct
public void myInit() {
setValidator(WSSecurityEngine.USERNAME_TOKEN, myUsernameTokenValidator);
setRequiredPasswordType(WSConstants.PASSWORD_TEXT);
}
}

JTATransactionManager Not Committing To Database

I will be working with a database and with a JMS queue so I decided to use JTATransactionManager (multiple resources).
I am using Spring Framework 3.2.3.RELEASE
Hibernate 4.2.1.Final
Glassfish 3.1.2.2
With JTATransactionManager nothing is committed to db.I tried JPATransactionManager it works fine.I don't get any exceptions with JTATransactionManager.Any idea what I am doing wrong?Thanks.
This is a piece of jpa config file
<jee:jndi-lookup id="dataSource" jndi-name="Test" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:packagesToScan="com.pinkshield.jpaTest.domain"
p:dataSource-ref="dataSource"
p:jpaPropertyMap-ref="jpaPropertyMap"
p:jpaVendorAdapter-ref="hibernateVendor" />
<util:map id="jpaPropertyMap">
<entry key="hibernate.hbm2ddl.auto" value="validate" />
<entry key="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect" />
<entry key="transaction.factory_class" value="org.hibernate.transaction.JTATransactionFactory" />
<entry key="transaction.manager_lookup_class"
value="org.hibernate.transaction.SunONETransactionManagerLookup" />
</util:map>
<bean id="hibernateVendor"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:showSql="true" />
<tx:jta-transaction-manager />
<context:component-scan base-package="com.pinkshield.jpaTest" />
This is my Generic Dao for JPA
package com.pinkshield.jpaTest;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
public class GenericDaoJpa<T> implements GenericDao<T>
{
private Class<T> queryClass;
protected EntityManager entityManager;
#PersistenceContext
public void setEntityManager(EntityManager entityManager)
{
this.entityManager = entityManager;
}
public GenericDaoJpa(Class<T> queryClass)
{
super();
this.queryClass = queryClass;
}
public T getNewInstance()
{
try
{
return getQueryClass().newInstance();
}
catch (InstantiationException e)
{
throw new RuntimeException("Error creating new instance of : " + getQueryClass().getName(), e);
}
catch (IllegalAccessException e)
{
throw new RuntimeException("Error creating new instance of : " + getQueryClass().getName(), e);
}
}
public Class<T> getQueryClass()
{
return queryClass;
}
public T get(Long id)
{
if (id == null)
{
return null;
}
else
{
return entityManager.find(queryClass, id);
}
}
#SuppressWarnings("unchecked")
public List<T> getAll()
{
return entityManager.createQuery("select o from " + queryClass.getName() + " o").getResultList();
}
public void save(T object)
{
entityManager.persist(object);
}
public void update(T object)
{
entityManager.merge(object);
}
public void delete(T object)
{
entityManager.remove(entityManager.merge(object));
}
}
This is UserDao
#Repository
public class UserDao extends GenericDaoJpa<User>
{
public UserDao()
{
super(User.class);
}
}
And this is my service code
#Service
public class UserServiceImpl implements IUserService{
#Autowired UserDao userDao;
#Override
#Transactional
public void saveUser(String name, String lastName)
{
User user=new User();
user.setLastName(lastName);
user.setName(name);
userDao.save(user);
}
}
I think you need to add <tx:annotation-driven/> to the context xml. That will run a context post processor that will wrap methods with #Transactional with an AOP method interceptor that provides the transaction behavior you're looking for.

Resources