我有三个实体,其中一个父母有两个孩子,但我这里只列出了两个实体。
@Entity
@Table(name = "person")
public class Person{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Long id;
@Column(name = "name")
private String name;
@OneToMany(fetch=FetchType.EAGER)
private Set<Phone> phones = new HashSet<Phone>();
@OneToMany(fetch=FetchType.EAGER)
@JoinColumn(name="person_id", referencedColumnName="id")
private List<Book> books = new ArrayList<Book>();
}
@Entity
@Table(name = "book")
public class Book{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Long id;
@Column(name="person_id")
private Long personId;
}
当我按照Hibernate标准运行并注意到SQL生成的日志时,它正在加入两个孩子 - 电话和书籍。我和这两个孩子之间没有任何关系。为什么从Hibernate标准生成的SQL查询尝试加入无关的两个孩子?我希望父母和孩子之间能够加入,而不是孩子之间。
Criteria criteria = session.createCriteria(Person.class)
.add(Restrictions.in("id", ids))
.setFetchMode("phones", FetchMode.JOIN).setFetchMode("books", FetchMode.JOIN)
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
result = criteria.list();
答案 0 :(得分:1)
如果您想使用标准,则需要为每种关系发布两个标准:
result = session.createCriteria(Person.class)
.add(Restrictions.in("id", ids))
.setFetchMode("phones", FetchMode.JOIN)
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
and
result = session.createCriteria(Person.class)
.add(Restrictions.in("id", ids))
.setFetchMode("books", FetchMode.JOIN)
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
否则您可以使用hql而不是条件并具有:
String hql= "select new list(person.phones, person.books) from Person person";
session.createQuery(hql).list();
修改强>
String hqlQuery = "select p from Person p left outer join p.phones as ph left outer join p.books as b";