1

@Transactional is not working in spring mvc. suppose i removed @Transactional annotation data is reached to RepositoryClass. Throwable targetException - org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(Object...) i need to reach data to repository class.

please help me., Thank you.

ServiceImplClass

   @Service("userService")
public class UserServiceImpl implements UserService{

    @Autowired
    UserRepository userRepository;

    public String saveUserData(User user,HttpSession session) {
        return userRepository.saveUserData(user);
    }
}

RepositoryClass:

@Component
@Transactional
public class UserRepository {

@Autowired
protected SessionFactory sessionFactory;

public SessionFactory getSessionFactory() {
    return sessionFactory;
}

public void setSessionFactory(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
}

public String saveUserData(User user) {

    final Session session = (Session) getSessionFactory();
    try {
        session.beginTransaction();
        Query query=session.createQuery("UPDATE User set user_Name =:userName,"
                + "reg_Date =:regDate,"
                + "img_Id=:imgId, emailId =:emailId");
        query.setParameter("userName", user.getUserName());
        query.setParameter("regDate", user.getRegDate());
        query.setParameter("imgId", user.getImgId());
        query.setParameter("emailId", user.getEmailId());
        session.save(user);
        session.getTransaction().commit();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

}

dispatcher-servlet.xml

  <?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"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                    http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
                    http://www.springframework.org/schema/context 
                    http://www.springframework.org/schema/context/spring-context-4.2.xsd
                    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
                    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
                    ">

    <context:annotation-config />
    <context:component-scan base-package="com.demo.app" />
    <mvc:default-servlet-handler />
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes" value="text/plain;charset=UTF-8" />
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <bean id="jspViewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/html/" />
        <property name="suffix" value="html" />
    </bean>

    <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/UserDB" />
        <property name="username" value="root" />
        <property name="password" value="password" />
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
            <list>
                <value>com.demo.app.model.User</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager" />

    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <bean
        class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <prop key="java.lang.Exception">Error</prop>
            </props>
        </property>
    </bean>
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="2097152" />
    </bean>
</beans>
Umapathi
  • 558
  • 2
  • 10
  • 25

5 Answers5

4

You're managing your transactions manually. That's the task of transaction manager. saveUserData should be like:

public User saveUserData(User user) {
    return (User)sessionFactory.getCurrentSession().merge(user);
}

And that's it. And you'll probably want to annotate your service with @Transactional and not repository.

Branislav Lazic
  • 14,388
  • 8
  • 60
  • 85
  • thank you for your replay.but it is not working getting Throwable java.lang.reflect.InvocationTargetException.getTargetException() – Umapathi Aug 04 '17 at 09:40
0

Your Repository don`t use @component annotation. and you use

<jpa:repositories base-package="your.package.put.repository"></jpa:repositories>

so, you already used

<bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>
0gam
  • 1,343
  • 1
  • 9
  • 21
0

First of all all transaction and session should managed by spring container is good practice so please don't manage session at your own, just use the existing session for data base querying. Now, for only your situation, try @Transactional annotation at Controller level and if it will work then you require some modification as per given below.

For web MVC Spring app should @Transactional go on controller or service?

0

Use @Transactional at Service level and when one of the operations doesnt work as it should(for example, an update operation returns 0 which means it failed) throw new RuntimeException(). If one of the operation fails, all other operations which are part of the transaction will be rolled back.

0

You are trying to use both container managed transaction and User managed transaction at the same time. Try to use only one at a time.

Either remove @Transactional annotation or remove the transaction statements from your method.

Ravi Sharma
  • 197
  • 1
  • 4