gpt4 book ai didi

java - 如何使用 hibernate 或 jpa 动态生成实体集合?

转载 作者:太空宇宙 更新时间:2023-11-04 14:57:01 25 4
gpt4 key购买 nike

我有以下两个 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,但是当我正在查看公式时,我愿意使用 hibernate 特定的解决方案

最佳答案

5 年前,但对于现在阅读本文的人来说:

@Formula附近,您应该添加: @ElementCollection(targetClass = X.class) 其中 X 是集合对象的类型。

关于java - 如何使用 hibernate 或 jpa 动态生成实体集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23077788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com