如果我有一个包含@OneToMany
的实体,请使用JPA如何选择该实体以及相关子项的一个子集?我不能使用@Where
或@Filter
批注。
更多详细信息我正在将我们的业务模型转换为更通用的内容,因此不必担心该示例没有合理的IRL。但是查询中有很多left join fetch
案例(比本示例更多)。朋友没有关系,只有一个字符串名称。
@Entity
public class Parent {
@Id
@GeneratedValue
private int parentId;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "friendId")
private Friend friends;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "parent", cascade = CascadeType.ALL)
private Set<Child> childrenSet = new HashSet<>();
}
@Entity
public class Child {
@Id
@GeneratedValue
private int childId;
private boolean blonde;
@ManyToOne(fetchType.LAZY, cascade = CascadeType.ALL)
private Parent parent;
}
@Query( "SELECT p " +
"FROM Parent p " +
"JOIN FETCH p.friends f " +
"LEFT JOIN FETCH p.childrenSet c " +
"WHERE f.name IS NOT NULL " +
"AND c.blonde = true")
List<Parent> getParentsWithListOfOnlyBlondeChildren();
测试类
@Transactional
@SpringBootTest
@RunWith(SpringRunner.class)
@DataJpaTest
public class TestParentRepo {
@PersistenceContxt
private EntityManager entityManager;
@Autowired
private ParentRepo parentRepo;
@Before
public void setup() {
Child c1 = new Child();
c1.setBlonde(true);
Child c2 = new Child();
c2.setBlonde(false);
Friend friend1 = new Friend();
friend1.setName("friend1");
Set<Child> children = new HashSet<>();
children.add(c1);
children.add(c2);
Parent parent1 = new Parent();
parent1.setFriends(friend1);
c1.setParent(parent1);
c2.setParent(parent1);
entityManager.persist(friend1);
entityManager.persist(parent1);
entityManager.persist(c1);
entityManager.persist(c2);
entityManager.flush();
entityManager.clear();
}
@Test
public void runTest() {
List<Parent> parent = parentRepo.getParentsWithListOfOnlyBlondeChildren();
System.out.println(parent);
}
}
现在调试我GET时是集合中有两个子对象的父对象。我WANT是只有c1的父母(金发= true)。
要过滤掉不符合条件的相关子实体,查询必须是什么?
我正在尝试避免:对于每个符合条件的父级查询子级,查询父级。
您不需要@Query
,如果您使用的是spring-data-jpa,则可以在存储库类中编写这样的方法
List<Parent> findByChildrenSet_Blonde(boolean isBlonde)
spring-data将通过查看方法名称来制定并执行查询。 _
表示依赖类字段
现在您可以像这样调用此函数
findByChildrenSet_Blonde(true)