Getting Transaction not successfully started exception using Spring Hibernate

前端 未结 2 2117
囚心锁ツ
囚心锁ツ 2021-02-10 05:06

I have a UserProfile entity which I need to save. after saving the entity in the database, I get the following exception:

Could not commit Hibernate transaction;         


        
2条回答
  •  独厮守ぢ
    2021-02-10 05:36

    I think you've fall a victim of dual transaction managements. If you are using Spring Transaction Management and Hibernate Transaction Management together in the same project, you are more likely to have this issue.

    Your code then should either be:

    Option 1. Hibernate transaction management

    public class HibernateUserProfileDAO implements UserProfileDAO {
        private org.hibernate.SessionFactory sessionFactory;
        public UserProfile getUserProfile(int userId) {
            org.hibernate.classic.Session session = sessionFactory.getCurrentSession();
            session.beginTransaction();
            UserProfile userProfile = new UserProfile();
            userProfile.setUserName("sury1");
            session.save(userProfile);
            session.getTransaction().commit();
            session.close();
            return userProfile;
        }
    }
    

    or Option 2. Spring transaction Management

    @Transactional
    public class HibernateUserProfileDAO implements UserProfileDAO {
        private org.hibernate.SessionFactory sessionFactory;
        public UserProfile getUserProfile(int userId) {
            org.hibernate.classic.Session session = sessionFactory.getCurrentSession();
            UserProfile userProfile = new UserProfile();
            userProfile.setUserName("sury1");
            session.save(userProfile);
            session.close();
            return userProfile;
        }
    }
    

提交回复
热议问题