Sql 如何过滤JPA2中的子实体集合?
我有两个实体在一对一的关系中Sql 如何过滤JPA2中的子实体集合?,sql,hibernate,jpa-2.0,Sql,Hibernate,Jpa 2.0,我有两个实体在一对一的关系中 @Entity public class Employee { @Id @GeneratedValue public long id; public String name; @OneToMany public Collection<Address> addresses = new ArrayList<Address>(); ...} @Entity public class Address { @Id @GeneratedValu
@Entity
public class Employee {
@Id @GeneratedValue
public long id;
public String name;
@OneToMany
public Collection<Address> addresses = new ArrayList<Address>();
...}
@Entity
public class Address {
@Id @GeneratedValue
public long id;
public String city;
...}
这个问题是我实际问题的简化版本
我的主要问题要复杂得多,它有多个子实体,对父实体的过滤使用sql函数
由于以上原因,我无法使用HQL或本机查询
因此,我正在使用EntityManager、CtiteriaBuilder等工具在“仅JPA 2”中寻找解决方案。在EclipseLink JPA中过滤关系需要使用本机API。方法是创建一个: 关于实体:
import org.eclipse.persistence.annotations.Customizer;
@Entity
@Customizer(ec.pack.z.pruebasDesarrollo.DC.class)
public class Employee {
@Id @GeneratedValue
public long id;
public String name;
@OneToMany
public Collection<Address> addresses = new ArrayList<Address>();
...}
import org.eclipse.persistence.annotations.Customizer;
@实体
@定制器(ec.pack.z.pruebasDesarrollo.DC.class)
公营雇员{
@Id@GeneratedValue
公共长id;
公共字符串名称;
@独身癖
公共收集3.5年后,这仍然是一个问题。但这通常应该适用于JPQLSELECT c FROM Cat c JOIN c.kittens k WHERE k.bodyWeight>:weight
这将获取Cat
,减少Kitten
的收集,就像RDBMS一样。@antoniosss:No它不会。它将返回Cat实体不筛选子实体。请参阅:
package ec.pack.z.pruebasDesarrollo;
import org.eclipse.persistence.config.DescriptorCustomizer;
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.expressions.Expression;
import org.eclipse.persistence.expressions.ExpressionBuilder;
import org.eclipse.persistence.mappings.OneToManyMapping;
public class DC implements DescriptorCustomizer {
@Override
public void customize(ClassDescriptor descriptor) throws Exception {
OneToManyMapping oneToManyMapping = (OneToManyMapping) descriptor.getMappingForAttributeName("addresses");
Expression exp = oneToManyMapping.buildSelectionCriteria();
ExpressionBuilder builder = exp.getBuilder();
Expression addedExpression = builder.getField("city").equal("New Delhi");
oneToManyMapping.setSelectionCriteria(exp.and(addedExpression));
}
}
import org.eclipse.persistence.annotations.Customizer;
@Entity
@Customizer(ec.pack.z.pruebasDesarrollo.DC.class)
public class Employee {
@Id @GeneratedValue
public long id;
public String name;
@OneToMany
public Collection<Address> addresses = new ArrayList<Address>();
...}