-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 
Author Message
 Post subject: Same query giving different results over time
PostPosted: Thu Oct 01, 2009 6:13 pm 
Newbie

Joined: Thu Oct 01, 2009 5:18 pm
Posts: 2
Hi,

I'm having a problem with Hibernate so I prepared the following test case to reproduce it easier.
I have 2 entities (Usuario and Grupo) with a OneToMany bidirectional relationship.
I'm doing some inserts followed by a query (checking if the insert worked).
I can retrieve the entity but can't follow the relationship:
Code:
Usuario u = (Usuario) em.createQuery("select u from Usuario u").getResultList().get(0);
System.out.println(u.toString());                        // OUTPUT: "Usuario[id=22]"
System.out.println(u.getGrupoCollection());              // OUTPUT: "null"

Checking the database I can see that the inserts worked.
If I run the same query again (finish the execution and start it again without the updates) both print outs work:
Code:
Usuario u = (Usuario) em.createQuery("select u from Usuario u").getResultList().get(0);
System.out.println(u.toString());                        // OUTPUT: "Usuario[id=22]"
System.out.println(u.getGrupoCollection());              // OUTPUT: "[Grupo[id=22]]"

I am manually deleting all records from database before the test case (only before inserts).
Both having the same id is just a coincidence (I've checked the database).
I have to finish the application and run it again. If I do the same query twice in the same runtime both return null for u.getGrupoCollection().
The database system is Postgres.

I'm new to JPA/Hibernate, so I am probably doing something wrong, but no idea what.
The entire code follows. Sorry if it is a lot of code, but I was afraid of keeping something important out.

Code:
public class Main {

    public static EntityManagerFactory emf = Persistence.createEntityManagerFactory("RaphaelPU");
    public static EntityManager em = emf.createEntityManager();

    public static void main(String[] args) {

        EntityTransaction tx = em.getTransaction();

        try {
            tx.begin();

            Usuario usuario = new Usuario();
            em.persist(usuario);

            Grupo grupo = new Grupo();
            grupo.setUsuarioId(usuario);
            em.persist(grupo);

            tx.commit();
        } finally {
            if (tx.isActive()) {
                tx.rollback();
                System.out.println("Bad news!");
            }
        }
        Usuario u = (Usuario) em.createQuery("select u from Usuario u").getResultList().get(0);
        System.out.println(u.toString());
        System.out.println(u.getGrupoCollection());
    }
}


Code:
@Entity
@Table(name = "usuario")
@NamedQueries({@NamedQuery(name = "Usuario.findAll", query = "SELECT u FROM Usuario u")})
public class Usuario implements Serializable {
    @Id
    @Basic(optional = false)
    @Column(name = "id")
    @SequenceGenerator(name="id", sequenceName="usuario_id_seq")
    @GeneratedValue(strategy=GenerationType.AUTO ,generator="id")
    private Integer id;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "usuarioId")
    private List<Grupo> grupoCollection;

    public Usuario() {
    }

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

    public Integer getId() {
        return id;
    }

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

    public List<Grupo> getGrupoCollection() {
        return grupoCollection;
    }

    public void setGrupoCollection(List<Grupo> grupoCollection) {
        this.grupoCollection = grupoCollection;
    }

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

    @Override
    public boolean equals(Object object) {
        if (!(object instanceof Usuario)) {
            return false;
        }
        Usuario other = (Usuario) 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 "Usuario[id=" + id + "]";
    }
}


Code:
@Entity
@Table(name = "grupo")
@NamedQueries({@NamedQuery(name = "Grupo.findAll", query = "SELECT g FROM Grupo g")})
public class Grupo implements Serializable {
    @Id
    @Basic(optional = false)
    @Column(name = "id")
    @SequenceGenerator(name="id", sequenceName="grupo_id_seq")
    @GeneratedValue(strategy=GenerationType.AUTO ,generator="id")
    private Integer id;
    @JoinColumn(name = "usuario_id", referencedColumnName = "id")
    @ManyToOne(cascade = CascadeType.ALL)
    private Usuario usuarioId;

    public Grupo() {
    }

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

    public Integer getId() {
        return id;
    }

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

    public Usuario getUsuarioId() {
        return usuarioId;
    }

    public void setUsuarioId(Usuario usuarioId) {
        this.usuarioId = usuarioId;
    }

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

    @Override
    public boolean equals(Object object) {
        if (!(object instanceof Grupo)) {
            return false;
        }
        Grupo other = (Grupo) 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 "Grupo[id=" + id + "]";
    }
}


Thanks,
Gustavo


Top
 Profile  
 
 Post subject: Re: Same query giving different results over time
PostPosted: Fri Oct 02, 2009 10:12 am 
Newbie

Joined: Thu Oct 01, 2009 5:18 pm
Posts: 2
I found a way to make it work. Doing, after the inserts: em.refresh(usuario);
I don't think it is a good idea, but at least it works.

If you have a better solution, please let me know.

Thanks,
Gustavo


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.