0

我有一个@ViewScopedbean,它调用一个@Statelessbean,它执行一个简单的查询以从我的数据库中返回一些值。

这应该足以在我每次加载页面时进行查询,这应该导致我在每次页面加载时始终更新数据。

但这不起作用,我不知道如何解决它!

我的查询返回旧值,即使在使用 MySql Workbench 更改它之后也是如此。(在 Workbench 上进行查询会返回正确的数据!)

这是代码:

DispensaListBean.java

package ManagedBeans;

import ejb.DispensaManager;
import ejb.DispensaManagerLocal;
import entity.Dispensa;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

/**
 *
 * @author stefano
 */
@ManagedBean
@ViewScoped
public class DispensaListBean {
    @EJB
    private DispensaManagerLocal dispensaManager;


    /**
     * Creates a new instance of DIspensaListBean
     */
    public DispensaListBean() {
    }

    public List<Dispensa> getTopDispense(){
        List<Dispensa> l = dispensaManager.findByVoto(DispensaManager.DESC);
        for(Dispensa d : l){
            System.out.println(d.getTitolo() + " | " + d.getVoto()); //This code prints ALWAY the old getVoto() value, it takes the new one just after restarting the server
        }
        return l;
    }

    public List<Dispensa> getDispense(){
        return dispensaManager.findAll();
    }

    public Dispensa getById(int i){
        return dispensaManager.findById(i);
    }
}

DispensaManager.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ejb;

import entity.Dispensa;
import facade.DispensaFacadeLocal;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;

/**
 *
 * @author stefano
 */
@Stateless
public class DispensaManager implements DispensaManagerLocal {

    public static final int ASC=0, DESC=1;

    @EJB
    private DispensaFacadeLocal dispensaFacade;

    @Override
    public java.util.List<Dispensa> findByVoto(int order) {
        return (order==DispensaManager.ASC) ? dispensaFacade.findByVotoAsc() : dispensaFacade.findByVotoDesc();
    }

    @Override
    public List findAll() {
        return dispensaFacade.findAll();
    }

    @Override
    public Dispensa findById(int id) {
        return dispensaFacade.find(id);
    }                
}

DispensaFacade.java

package facade;

import entity.Dispensa;
import entity.Post;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

/**
 *
 * @author stefano
 */
@Stateless
public class DispensaFacade extends AbstractFacade<Dispensa> implements DispensaFacadeLocal {
    @PersistenceContext(unitName = "UNILIFE-ejbPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public DispensaFacade() {
        super(Dispensa.class);
    }

    @Override
    public List<Dispensa> findByVotoDesc() {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Dispensa> q = cb.createQuery(Dispensa.class);
        Root<Dispensa> c = q.from(Dispensa.class);
        q.select(c);
        q.where(cb.isNotNull(c.get("datiFile")));
        q.orderBy(cb.desc(c.get("voto")));
        TypedQuery<Dispensa> typedQuery = em.createQuery(q);
        return typedQuery.getResultList();
    }

    @Override
    public java.util.List<Dispensa> findByVotoAsc() {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Dispensa> q = cb.createQuery(Dispensa.class);
        Root<Dispensa> c = q.from(Dispensa.class);
        q.select(c);
        q.where(cb.isNotNull(c.get("datiFile")));
        q.orderBy(cb.asc(c.get("voto")));
        TypedQuery<Dispensa> typedQuery = em.createQuery(q);
        return typedQuery.getResultList();
    }
}

Dispensa.java

package entity;

import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

/**
 *
 * @author stefano
 */
@Entity
@Table(name = "Dispensa")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Dispensa.findAll", query = "SELECT d FROM Dispensa d"),
    @NamedQuery(name = "Dispensa.findById", query = "SELECT d FROM Dispensa d WHERE d.id = :id"),
    @NamedQuery(name = "Dispensa.findByTitolo", query = "SELECT d FROM Dispensa d WHERE d.titolo = :titolo"),
    @NamedQuery(name = "Dispensa.findByDescrizione", query = "SELECT d FROM Dispensa d WHERE d.descrizione = :descrizione"),
    @NamedQuery(name = "Dispensa.findByTag", query = "SELECT d FROM Dispensa d WHERE d.tag = :tag"),
    @NamedQuery(name = "Dispensa.findByData", query = "SELECT d FROM Dispensa d WHERE d.data = :data"),
    @NamedQuery(name = "Dispensa.findByVoto", query = "SELECT d FROM Dispensa d WHERE d.voto = :voto"),
    @NamedQuery(name = "Dispensa.findByNumVoti", query = "SELECT d FROM Dispensa d WHERE d.numVoti = :numVoti"),
    @NamedQuery(name = "Dispensa.findByNumDownloads", query = "SELECT d FROM Dispensa d WHERE d.numDownloads = :numDownloads")})
public class Dispensa implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @NotNull
    @Column(name = "id")
    private Integer id;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 50)
    @Column(name = "titolo")
    private String titolo;
    @Size(max = 255)
    @Column(name = "descrizione")
    private String descrizione;
    @Size(max = 255)
    @Column(name = "tag")
    private String tag;
    @Basic(optional = true)
    @NotNull
    @Lob
    @Column(name = "datiFile")
    private byte[] datiFile;
    @Basic(optional = false)
    @NotNull
    @Column(name = "data")
    @Temporal(TemporalType.DATE)
    private Date data;
    @Basic(optional = false)
    @NotNull
    @Column(name = "voto")
    private int voto;
    @Basic(optional = false)
    @NotNull
    @Column(name = "numVoti")
    private int numVoti;
    @Basic(optional = false)
    @NotNull
    @Column(name = "numDownloads")
    private int numDownloads;
    @JoinTable(name = "Scaricati", joinColumns = {
        @JoinColumn(name = "dispensa", referencedColumnName = "id")}, inverseJoinColumns = {
        @JoinColumn(name = "utente", referencedColumnName = "username")})
    @ManyToMany(fetch = FetchType.LAZY)
    private Collection<Utente> downloaders;
    @JoinColumn(name = "materia", referencedColumnName = "id")
    @ManyToOne(optional = true)
    private Materia materia;
    @JoinColumn(name = "autore", referencedColumnName = "username")
    @ManyToOne(optional = false)
    private Utente autore;

    public Dispensa() {
    }

    public Dispensa(Integer id) {
        this.id = id;
    }

    public Dispensa(Integer id, String titolo, byte[] datiFile, Date data, int voto, int numVoti, int numDownloads) {
        this.id = id;
        this.titolo = titolo;
        this.datiFile = datiFile;
        this.data = data;
        this.voto = voto;
        this.numVoti = numVoti;
        this.numDownloads = numDownloads;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getTitolo() {
        return titolo;
    }

    public void setTitolo(String titolo) {
        this.titolo = titolo;
    }

    public String getDescrizione() {
        return descrizione;
    }

    public void setDescrizione(String descrizione) {
        this.descrizione = descrizione;
    }

    public String getTag() {
        return tag;
    }

    public void setTag(String tag) {
        this.tag = tag;
    }

    public byte[] getDatiFile() {
        return datiFile;
    }

    public void setDatiFile(byte[] datiFile) {
        this.datiFile = datiFile;
    }

    public Date getData() {
        return data;
    }

    public void setData(Date data) {
        this.data = data;
    }

    public int getVoto() {
        return voto;
    }

    public void setVoto(int voto) {
        this.voto = voto;
    }

    public int getNumVoti() {
        return numVoti;
    }

    public void setNumVoti(int numVoti) {
        this.numVoti = numVoti;
    }

    public int getNumDownloads() {
        return numDownloads;
    }

    public void setNumDownloads(int numDownloads) {
        this.numDownloads = numDownloads;
    }

    @XmlTransient
    public Collection<Utente> getDownloaders() {
        return downloaders;
    }

    public void setDownloaders(Collection<Utente> utenteCollection) {
        this.downloaders = utenteCollection;
    }

    public Materia getMateria() {
        return materia;
    }

    public void setMateria(Materia materia) {
        this.materia = materia;
    }

    public Utente getAutore() {
        return autore;
    }

    public void setAutore(Utente autore) {
        this.autore = autore;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Dispensa)) {
            return false;
        }
        Dispensa other = (Dispensa) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "entity.Dispensa[ id=" + id + " ]";
    }

}

现在,我在使用其他实体和方法之前也遇到过这个问题,我通过刷新实体解决了这个问题,但是如果我每次加载页面时都从数据库中获取实体,为什么要在这种情况下刷新实体呢?

简直是胡说八道!

4

6 回答 6

3

从代码本身看来,您自己并没有进行任何显式缓存。@ViewScoped@RequestScoped并且isPostback在这里都无关紧要,相反,这些范围的目的实际上是进行缓存,而不是让支持 bean 每次都调用服务。

然而,这几乎与你的问题相反。

如果您从实体管理器获得过时的实体,则几乎总是使用 L2 缓存。您是否在persistence.xml 中配置了任何内容?您使用哪种 JPA 实现?

同样重要的是,您在哪里以及如何更新您的数据?给出的代码没有显示它。您确实提到了这一点“即使在使用 MySql Workbench 进行更改之后

在使用 JPA 2 级 (L2) 缓存的情况下,JPA 将从该缓存中获取实体。如果没有应对措施,它只会跟踪通过 JPA 修改这些实体的更改。如果您自己更新基础数据,无论是直接通过 JDBC 还是通过其他一些外部系统(如 MySql Workbench),JPA 都不会知道这些更改。

于 2012-05-06T20:14:29.733 回答
1

我的直觉是你有某种陈旧的缓存。

你读过这篇文章吗?

我将首先关注您的会话 Bean。创建一个没有 JSF 页面额外复杂性的测试工具。

我期待您的无状态 bean 的默认事务行为是“明智的”,但我现在想知道是否使用

@TransactionAttribute(TransactionAttributeType.REQUIRED)

可能会解决您的问题。

于 2012-05-06T20:16:53.473 回答
1

这很可能是由 MySQL 的默认隔离级别 REPEATABLE READ 引起的。

这意味着在您结束(提交、回滚)“自己的”事务之前,您不会看到其他事务所做的更改(请记住:SELECT 已经启动了事务)

我假设 EJB 连接取自连接池,因此启动的事务永远不会正确结束。在从您的 Web 应用程序中运行选择之前尝试发出提交或回滚。

对于永久解决方案,您可以通过配置连接池来更改默认隔离(大多数都允许这样做),通过在连接上调用 setTransactionIsolation() 或通过更改 MySQL 中的默认隔离级别来更改事务级别。

于 2012-05-06T20:18:04.793 回答
1

您是否使用休眠作为您的 EntityManager?如果是这样,它可能正在使用会话缓存并存储您的对象。在这种情况下,如果您通过 SQL 或通过不同的会话更改数据,您可能需要在对象上调用“刷新”以获取更改。

于 2012-05-06T20:43:15.303 回答
0

您是否尝试将 bean 更改为@RequestScoped

于 2012-05-05T11:47:21.090 回答
-1

您需要知道您的页面是否为回发,http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/javax/faces/render/ResponseStateManager.html

类似的东西

ResponseStateManager rsm = FacesContext.getCurrentInstance().getRenderKit().getResponseStateManager();  

if (!rsm.isPostback(FacesContext.getCurrentInstance())) {  

    //do some stuff  
}  
于 2012-05-04T16:02:09.333 回答