过滤器不初始化EntityManager

时间:2011-10-28 20:18:53

标签: java-ee jpa jsf-2 jpa-2.0 servlet-filters

我尝试在视图模式中使用Open Session,但是每当我尝试捕捉EntityManager中的ManagedBean entityManagerNULL时,我就是这样的我在做:

package filters;

// imports..    


public class JPAFilter implements Filter {

    private EntityManagerFactory factory;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        EntityManager entityManager = this.factory.createEntityManager();
        request.setAttribute("entityManager", entityManager);
        entityManager.getTransaction().begin();

        chain.doFilter(request, response);

        try {
            entityManager.getTransaction().commit();
        } catch (Exception e) {
            entityManager.getTransaction().rollback();
            throw new ServletException(e);
        } finally {
            entityManager.close();
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.factory = Persistence.createEntityManagerFactory("copadomundo");

    }

    @Override
    public void destroy() {
        this.factory.close();
    }

}

这是我的ManagedBean:

package managedbeans;

// imports ..

@ManagedBean
public class PlayerBean {

    @ManagedProperty(value = "#{entityManager}")
    private EntityManager entityManager;

    private Player player = new Player();

    private Long teamID;

    private List<Player> players = new ArrayList<Player>();

    public void add() {
        TeamRepository selecaoRepository = new TeamRepository(this.entityManager);
        Team selecao = selecaoRepository.search(this.teamID);
        this.player.setTeam(selecao);

        PlayerRepository playerRepository = new PlayerRepository(this.entityManager);
        playerRepository.adiciona(this.player);

        this.player = new Player();
        this.players = null;
    }

    public void remove(Player player) {
        PlayerRepository repository = new PlayerRepository(this.entityManager);
        repository.remove(player);
        this.players = null;
    }

    // GETTERS AND SETTERS
    public List<Player> getPlayeres() {
        if (this.players == null) {

            PlayerRepository repository = new PlayerRepository(
                    this.entityManager);
            this.players = repository.getPlayeres();
        }
        return this.players;
    }

    public EntityManager getEntityManager() {
        return entityManager;
    }

    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    public Player getPlayer() {
        return player;
    }

    public void setPlayer(Player player) {
        this.player = player;
    }

    public Long getTeamID() {
        return teamID;
    }

    public void setTeamID(Long teamID) {
        this.teamID = teamID;
    }

    public void setPlayeres(List<Player> players) {
        this.players = players;
    }
}

这是我的web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>WorldCup</display-name>
    <welcome-file-list>
        <welcome-file>index.xhtml</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>
    <filter>
        <filter-name>LoginFilter</filter-name>
        <filter-class>jpa.LoginFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>LoginFilter</filter-name>
        <servlet-name>Faces Servlet</servlet-name>
    </filter-mapping>
    <filter>
        <filter-name>JPAFilter</filter-name>
        <filter-class>jpa.JPAFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>JPAFilter</filter-name>
        <servlet-name>Faces Servlet</servlet-name>
    </filter-mapping>
    <error-page>
        <exception-type>java.lang.Exception</exception-type>
        <location>/error.xhtml</location>
    </error-page>
</web-app>

知道为什么会这样吗?

更新 在关于JPA,Hibernate和EJB的每个地方搜索之后,我终于找到了一个很好的教程(按照这个顺序来理解正在做什么,好吗?):

Install and Configure MySQL for Eclipse and Oracle Glassfish 3.1

Building a User Registration Form using JSF 2.0

Validation and Conversion of Data Using JSF 2.0

Using EJB 3.0 and JPA 2.0 for Database Persistence

1 个答案:

答案 0 :(得分:6)

仅当您的PlayerBean也是请求作用域时,这才有效。如果它是视图作用域,则忽略任何手动创建的请求范围属性,而不是仅仅因为不允许此构造而注入。您只能注入与接受者相同或更广范围的JSF托管属性。

我根据您的问题历史知道您正在使用Glassfish 3.为什么不直接使用EJB?这样容器就会担心交易本身,你根本不需要这样的过滤器。您可以按@PersistenceContext注入EntityManager

这很简单。只需创建以下EJB类:

@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));
    }

    // ...
}

(Glassfish 3无需进一步配置)

然后,您可以在JSF托管bean中使用它:

@ManagedBean
@ViewScoped
public class PlayerBean {

    private List<Player> players;

    @EJB
    private PlayerService playerService;

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

    // ...
}