2016-11-19 103 views
1

我正在與春天和冬眠的Vaadin Java項目工作。我的下一個實體在我的項目:Hibernate使正確的數據庫查詢,但返回null實體

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會返回空對象。

我不能得到錯誤。 任何人都可以幫助我嗎?

回答

1

如果你想使用命名查詢,那麼你應該使用它作爲:

@NamedQuery(name = "obtenerAreaPorId", query = "SELECT a FROM AreaFuncional a where a.id= :id") }) 

getSessionFactory().getNamedQuery("obtenerAreaPorId").setLong("id", id) 
+0

我認爲這兩種可能性都可以。我有許多其他命名查詢以相同的方式完成 –

0

我認爲你無法通過id參數; 測試這一個:

@NamedQuery(name = "obtenerAreaPorId", query = "SELECT a FROM AreaFuncional a where a.id=:id") }) 

getSessionFactory().getNamedQuery("obtenerAreaPorId").setParameter("id",myId) 
相關問題