无法在Hibernate中检索@OneToMany关系

时间:2015-07-23 13:47:06

标签: hibernate java-ee jpa

我有这两个实体:

C++

我尝试使用以下代码阅读项目列表

@Entity
@Table(name = "PROJECT")
public class Project {

  public Project () {}

  public Project(Long id, Set<Location> locations) {
        this.id = id;
        this.locations= locations;
  }

  @OneToMany(mappedBy = "project", fetch = FetchType.LAZY, cascade =    CascadeType.ALL, orphanRemoval = true)
  private Set<Location> locations= new HashSet<>();

  //others fields, getters and setters follow
}

@Entity
@Table(name = "LOCATION")
public class Location {

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "ID_PROJECT", nullable = false)
    private Project project;

    //others fields, getters and setters follow
}

并且hibernate执行此查询

CriteriaQuery<Project> cq = criteriaBuilder.createQuery(Project.class);
Root<Progetto> r = cq.from(Project.class);

cq.multiselect(r.<Long>get("id"), r.<Location> get("locations"));
TypedQuery<Project> q = entityManager.createQuery(cq);
q.getResultList();

这显然是错误的,因为'。作为col_1_0_'。 为什么Hibernate会产生错误的查询?

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

试试这个:

@OneToMany(mappedBy = "project", fetch = FetchType.LAZY, cascade CascadeType.ALL, orphanRemoval = true)
@MapKey(name="ID_PROJECT")
@Column(name="ID_LOCATION")
private Set<Location> locations= new HashSet<>();