休眠ManyToMany选择 [英] Hibernate ManyToMany select

查看:95
本文介绍了休眠ManyToMany选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上下文:我有两个表Secret_Agent和Secret_Mission.两者之间具有@ManyToMany关系,因为可以给许多秘密特工执行相同的秘密任务,并且可以给同一个秘密特工执行许多秘密任务.

Context: I have two tables Secret_Agent and Secret_Mission. Both have a @ManyToMany relationship with each other since many secret agents can be given to perform the same secret mission and the same secret agent can be given many secret missions.

表SECRET_AGENT

Table SECRET_AGENT

SecretAgentId,SecrentAgentName列

Columns SecretAgentId, SecrentAgentName

表SECRET_MISSION

Table SECRET_MISSION

SecretMissionId,SecrentMissionName,SecretMissionStatus列

Columns SecretMissionId, SecrentMissionName, SecretMissionStatus

加入表格

SECRET_AGENT_MISSION

SECRET_AGENT_MISSION

列:SecretAgentId,SecretMissionId

Columns: SecretAgentId,SecretMissionId

Java代码:

Secret_Agent类{. .

class Secret_Agent { . . .

@ManyToMany(级联= CascadeType.ALL)@JoinTable(名称= "SECRET_AGENT_MISSION",joinColumns = {@ @JoinColumn(name = "SecretAgentId")},inverseJoinColumns = {@JoinColumn(name = "SecretMissionId")}私人名单任务; . . . }

@ManyToMany(cascade = CascadeType.ALL) @JoinTable(name = "SECRET_AGENT_MISSION", joinColumns = { @JoinColumn(name = "SecretAgentId") }, inverseJoinColumns = { @JoinColumn(name = "SecretMissionId") } private List missions; . . . }

Secret_Mission类{. .

class Secret_Mission { . . .

@ManyToMany(mappedBy ="missions")私有列表代理; . . . }

@ManyToMany(mappedBy = "missions") private List agents; . . . }

问题:我正在尝试获取状态为=有效的所有特工和特工任务.但是下面的查询仅向我查询任务状态为有效"的特工.

problem: I`m trying to get all Agents and agents mission with status = Active. But query below retrieve me just Agents who had missions with status Active.

 @Query(FROM FROM Secret_Agent sa "
            + "LEFT JOIN FETCH sa.missions sm"
            + "WHERE sm.status = "ACTIVE" ")

任务状态可以是存档"或活动". 我只需要任务状态为ACTIVE的所有秘密特工或任务状态为空的SecretAgent实体

There mission status can be Archieve or Active. I need just All Secret Agents with missions which had status ACTIVE or just SecretAgent entity with empty mission

推荐答案

可以通过以下方式使用@Where注释两次映射关联来解决此问题.

It is possible to solve this problem by mapping your association twice in the following way with @Where annotation.

@ManyToMany(mappedBy = "agents") 
@Where(clause = "status = 'ACTIVE'")
private List activeMissions

@ManyToMany(mappedBy = "agents")
private List missions

完整的解释可以在这里找到 https://Thoughts-on-java.org/hibernate-tips-filter-entities-mapped-association/

Complete explanation can be found here https://thoughts-on-java.org/hibernate-tips-filter-entities-mapped-association/

这篇关于休眠ManyToMany选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆