1

I'm developing a sample Spring application deployed on Tomcat.

Dao class:

@Repository
public class UserDao implements IUserDao
{
    @PersistenceContext
    private EntityManager manager;
    
    @Override
    public User getUserById(Integer id)
    {
     User u = manager.find(User.class, id);
     
     return u;
    }
    
    @Override
    public User getUserByName(String name)
    {
        Query q = manager.createQuery("SELECT u FROM User u WHERE u.name = ?");
        q.setParameter(1, name);
        
        @SuppressWarnings("unchecked")
        List<User> list = (List<User>) q.getResultList();
        
        if(!list.isEmpty())
         return list.get(0);
        
        return null;
    }

    @Override
    public void addUser(User u)
    {
        manager.persist(u);
        
    }
}

Controller Class:

@Controller
public class HomeController
{
    @Autowired
    private IUserDao ud;
    
    
    @RequestMapping(value = "/page")
    public String getPage()
     {

        User u = new User();
        u.setName("Harry");
        ud.addUser(u);
        return "page";
    }
}

When requesting /page I keep getting the following exception:

No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call.

My question is why does this happen?
And why the same does not happen if I call another Dao method which does not involve the call of persist method on the Entity Manager?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
GionJh
  • 2,742
  • 2
  • 29
  • 68
  • 1
    1. because you don't have a transaction available for the current thread, 2. because Spring allows executing select queries without a transaction (although I would avoid that as well). – JB Nizet Oct 31 '15 at 13:16
  • As far as I know execution of a query , being that a read or write query is managed by SQL DBMS as a normal transaction,so why bother with explicitily create one, am I wrong ? Thanks for your time – GionJh Oct 31 '15 at 13:19
  • I don't understand what you're asking: does the dbms manage queries as normal queries? What does that mean? This is irrelevant anyway, since that exception is not thrown by the DBMS, but by Spring. – JB Nizet Oct 31 '15 at 13:24
  • I got the same problem. After I removed the "init()" method, it works fine to me. This init() method was declared as "default-init-method". – Thach Van May 17 '16 at 06:52

0 Answers0