【发布时间】:2014-04-15 08:00:30
【问题描述】:
我有以下两个jpa hibernate实体,
@Entity
public class Product {
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name="uuid", strategy="uuid2")
private String id;
@ManyToOne
private Type type;
@ManyToOne
private Attribute attribute;
}
和
@Entity
public class ProductFamily {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name="uuid", strategy="uuid2")
private String id;
@ManyToMany
@Formula("("
+ " SELECT t.id "
+ " FROM Type t "
+ " WHERE t.id IN ( "
+ " SELECT p.type_id "
+ " FROM product p"
+ " WHERE p.family_id = id"
+ " ) "
+ " order by t.value asc "
+ " )")
private Set<Type> types;
@ManyToMany()
@Formula("("
+ " SELECT a.id "
+ " FROM Attribute a "
+ " WHERE a.id IN ( "
+ " SELECT p.attribute_id "
+ " FROM product p"
+ " WHERE p.family_id = id"
+ " ) "
+ " order by a.value asc "
+ " )")
private Set<Attribute> attributes;
@OneToMany(mappedBy="family")
@LazyCollection(LazyCollectionOption.FALSE)
private Set<Product> products;
}
我正在尝试将产品系列中的类型和属性字段生成为系列产品的类型和属性集。 (注意,类型和属性类本身就是实体)
当我得到以下公式时,不允许使用以下公式
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:1225)
... 51 more
Caused by: org.hibernate.MappingException: Could not determine type for: java.util.Set, at table: ProductFamily, for columns: [org.hibernate.mapping.Formula( ( SELECT t.id FROM Type t WHERE t.id IN ( SELECT p.type_id FROM product p WHERE p.family_id = id ) ) )]
at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:336)
... 56 more
这似乎表明将公式的结果映射到一组实体时存在问题
这可以用公式吗?如果有怎么办?
如果没有,有没有标准的方法来做这种事情?如果不是,您会推荐什么更好的方法。
最后,我希望尽可能使用 jpa,但由于我已经在查看公式,因此我愿意使用特定于休眠的解决方案
【问题讨论】:
-
独立尝试 @Formula 中的 sql 以检查它们是否有效??
-
是的,我测试了它,当只有一个结果时它可以工作,但是当我有多个嵌套值时,我得到
ERROR: more than one row returned by a subquery used as an expression -
在 JPA 中,如果您期望只有一个结果集,您可以使用 query.getSingleResult()。否则,如果本机 SQL 出现问题,我认为您需要先独立修复。
标签: java hibernate jpa many-to-many hibernate-annotations