我正在使用spring和hibernate在Vaadin java项目中工作。我的项目中有下一个实体:
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>();
}
....
然后我有下一个查询:
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;
}
当我执行查询时,我得到了正确的数据库mysql查询:
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=?
如果我在控制台中执行mysql语句,我会得到正确答案,但Hibernate会返回null对象。
我无法得到错误。 有人可以帮我吗?
答案 0 :(得分:1)
如果要使用命名查询,则应将其用作:
@NamedQuery(name = "obtenerAreaPorId", query = "SELECT a FROM AreaFuncional a where a.id= :id") })
和
getSessionFactory().getNamedQuery("obtenerAreaPorId").setLong("id", id)
答案 1 :(得分:0)
我认为你不能传递id参数; 测试一下:
@NamedQuery(name = "obtenerAreaPorId", query = "SELECT a FROM AreaFuncional a where a.id=:id") })
getSessionFactory().getNamedQuery("obtenerAreaPorId").setParameter("id",myId)