我在OneToMany关系中有两个实体。
@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;
...}
我想用雇员领域的一些简单标准来获取员工(这很好,不是问题),它应该只包含那些在城市领域有“新德里”的地址(这就是问题)。 / p>
JPA 2中等同于以下的东西
from Cat as cat
left join cat.kittens as kitten
with kitten.bodyWeight > 10.0
这个问题是我实际问题的简化版本。
我的主要问题如果复杂得多,它有多个子实体,并且父实体上的过滤使用sql函数。
由于上述原因,我无法使用HQL或Native Queries。
所以我正在使用EntityManager,CtiteriaBuilder以及所有这些来寻找“JPA 2 ONLY”中的解决方案。
答案 0 :(得分:0)
在EclipseLink JPA中过滤关系需要使用本机API。完成此操作的方法是创建一个DescriptorCustomizer:
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>();
...}