调用SQL查询将返回旧值

时间:2012-05-04 15:19:20

标签: java sql jsf java-ee orm

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

这应该足以在我每次加载页面时进行查询,这应该会让我总是在每次加载页面时更新数据。

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

我的查询返回旧值,即使在使用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 + " ]";
    }

}

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

这只是废话!

6 个答案:

答案 0 :(得分:3)

从代码本身来看,你自己看起来并不是在做任何明确的缓存。 @ViewScoped@RequestScopedisPostback在这里都不相关,相反,这些范围的目的实际上是进行缓存,而不是让支持bean调用服务每一次。

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

如果您从实体管理器获得过时的实体,它几乎总是L2缓存的情况。你在persistence.xml中配置了什么?你使用哪种JPA实现?

同样重要的是,您在何处以及如何更新数据?给出的代码没有显示它。即使在使用MySql Workbench 更改它之后,你也会提到这个“

在使用JPA Level 2(L2)缓存的情况下,JPA将从此缓存中获取实体。如果没有应对措施,只有通过JPA修改后,它才会跟踪对这些实体的更改。如果您自己直接通过JDBC或通过其他一些外部系统(如MySql Workbench)更新基础数据,JPA将不会意识到这些更改。

答案 1 :(得分:1)

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

您是否阅读过this article

我首先关注你的会话Bean。在没有JSF页面的额外复杂性的情况下创建测试工具。

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

@TransactionAttribute(TransactionAttributeType.REQUIRED)

可能会解决您的问题。

答案 2 :(得分:1)

最有可能的原因是MySQL的默认隔离级别是REPEATABLE READ。

这意味着,在您结束(提交,回滚)自己的&#34;之前,您不会看到其他交易所做的更改。 transaction(记住:SELECT已经启动了一个事务)

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

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

答案 3 :(得分:1)

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

答案 4 :(得分:0)

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

答案 5 :(得分:-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  
}