Filter do not initialize EntityManager

前端 未结 1 1458
借酒劲吻你
借酒劲吻你 2020-12-10 20:59

I trying to use the Open Session in View pattern, but everytime I try to catch the EntityManager in my ManagedBean the entityManager c

1条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-10 21:32

    That will only work if your PlayerBean is also request scoped. If it is view scoped, then any manually created request scoped attributes are ignored and not injected simply because this construct is not allowed. You can only inject a JSF managed property of the same or broader scope than the acceptor.

    I know based on your question history that you're using Glassfish 3. Why don't you just use an EJB? This way the container will worry about transactions itself and you don't need to have such a filter at all. You can inject the EntityManager by @PersistenceContext.

    It's pretty simple. Just create the following EJB class:

    @Stateless
    public class PlayerService {
    
        @PersistenceContext
        private EntityManager em;
    
        public Player find(Long id) {
            return em.find(Player.class, id);
        }
    
        public List list() {
            return em.createQuery("SELECT p FROM Player p", Player.class).getResultList();
        }
    
        public void create(Player player) {
            em.persist(player);
        }
    
        public void update(Player entity) {
            em.merge(player);
        }
    
        public void delete(Player player) {
            em.remove(em.contains(player) ? player : em.merge(player));
        }
    
        // ...
    }
    

    (no further configuration is necessary on Glassfish 3)

    You can then use it as follows in your JSF managed bean:

    @ManagedBean
    @ViewScoped
    public class PlayerBean {
    
        private List players;
    
        @EJB
        private PlayerService playerService;
    
        @PostConstruct
        public void init() {
            players = playerService.list();
        }
    
        // ...
    }
    

    0 讨论(0)
提交回复
热议问题