Reputation: 11
I'm working in a Vaadin java project with spring and hibernate. I have the next Entity in my project:
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import org.hibernate.annotations.NamedQueries;
import org.hibernate.annotations.NamedQuery;
@Entity
@NamedQueries({
@NamedQuery(name = "listarAreas", query = "SELECT a FROM AreaFuncional a"),
@NamedQuery(name = "obtenerAreaPorId", query = "SELECT a FROM AreaFuncional a where a.id=?") })
public class AreaFuncional implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String nombre;
@ManyToOne(cascade = { CascadeType.ALL })
@JoinColumn(name = "area_pertenencia_id")
private AreaFuncional areaPertenencia;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private Set<AreaFuncional> subAreas;
@OneToMany(fetch = FetchType.LAZY)
private Set<Empleado> empleados;
private String telefonos;
private String email;
public AreaFuncional() {
this.subAreas = new HashSet<AreaFuncional>();
this.empleados = new HashSet<Empleado>();
}
....
Then I have the next query:
public AreaFuncional obtenerAreaPorId(Long id) {
AreaFuncional area = (AreaFuncional)
getSessionFactory().getNamedQuery("obtenerAreaPorId").setLong(0, id)
.uniqueResult();
if (area == null)
throw new RuntimeException("No existe el area con id " + id);
return area;
}
When I execute the query, I get the correct mysql query for database:
01:49:11,785 DEBUG http-bio-8080-exec-42 hibernate.SQL:109 - select areafuncio0_.id as id1_0_, areafuncio0_.area_pertenencia_id as area_per5_0_, areafuncio0_.email as email2_0_, areafuncio0_.nombre as nombre3_0_, areafuncio0_.telefonos as telefono4_0_ from AreaFuncional areafuncio0_ where areafuncio0_.id=?
If I execute the mysql statement in console, I get the correct answer, but Hibernate returns null object.
I can't get the error. Can anybody help me with this?
Upvotes: 1
Views: 903
Reputation: 1645
I think you can not pass the id parameter; Test this one :
@NamedQuery(name = "obtenerAreaPorId", query = "SELECT a FROM AreaFuncional a where a.id=:id") })
getSessionFactory().getNamedQuery("obtenerAreaPorId").setParameter("id",myId)
Upvotes: 0
Reputation: 12174
If you want to use named query then you should use it as:
@NamedQuery(name = "obtenerAreaPorId", query = "SELECT a FROM AreaFuncional a where a.id= :id") })
and
getSessionFactory().getNamedQuery("obtenerAreaPorId").setLong("id", id)
Upvotes: 1