Filter do not initialize EntityManager

ε祈祈猫儿з 提交于 2019-11-28 11:40:28

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<Player> 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<Player> players;

    @EJB
    private PlayerService playerService;

    @PostConstruct
    public void init() {
        players = playerService.list();
    }

    // ...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!