Using JPA entities in JSF. Which is the best strategy to prevent LazyInitializationException?

后端 未结 6 1929
执念已碎
执念已碎 2020-11-28 11:48

Would like to hear experts on best practice of editing JPA entities from JSF UI.

So, a couple of words about the problem.

Imagine I have the persisted object

6条回答
  •  余生分开走
    2020-11-28 12:16

    Open Session in View design pattern can be easy implemented in Java EE environment (with no dependency to hibernate, spring or something else out side Java EE). It is mostly the same as in OpenSessionInView, but instead of Hibernate session you should use JTA transaction

    @WebFilter(urlPatterns = {"*"})
    public class JTAFilter implements Filter{
    
        @Resource
        private UserTransaction ut;
    
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
    
        }
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            try{
               ut.begin();
               chain.doFilter(request, response);
            }catch(NotSupportedException | SystemException e){
                throw new ServletException("", e);
            } finally {
                try {
                   if(ut.getStatus()!= Status.STATUS_MARKED_ROLLBACK){
                       ut.commit();
                   }
                } catch (Exception e) {
                    throw new ServletException("", e);
                }
           }
      }
    
      @Override
      public void destroy() {
    
      }
    }
    

提交回复
热议问题