我正在开发一个部署在Tomcat上的示例Spring应用程序。
道上课:@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
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";
}
}
请求/页面时,我不断收到以下异常:
No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call.
我的问题是为什么会发生这种情况? 如果我调用另一个不涉及在实体管理器上调用持久化方法的Dao方法,为什么不会发生同样的情况?