JPA从具有多对多关联的集合中进行选择

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (254)

我有2个具有多对多关联的实体类。

ModPm:

@Entity
@Table(name = "MOD_PM")
public class ModPm extends WebPageObject implements Serializable, IDBNamedEntity {

    private static final long serialVersionUID = 1L;

    public final static String Q_GET_WITHOUT_STATUS_FOR_SCOPE = "ModPm.getWithoutStatusForScope";

    @Id
    private long id;
    ....
    @ManyToMany
    @JoinTable(name = "MOD_PM_SCOPE_TYPES",
            joinColumns = @JoinColumn(name = "PM_ID"),
            inverseJoinColumns = @JoinColumn(name = "SCOPE_TYPE_ID")
    )
    private List<ModScopeType> modScopeTypes;

ModScopeType:

@Entity
@Table(name = "MOD_SCOPES")
@Cacheable
public class ModScopeType extends WebPageObject implements Serializable {

    private static final long serialVersionUID = 1L;

    public final static String Q_GET_ALL = "ModScopeType.getAll";

    @Id
    @Column(name = "ID")
    private long id;
    ....
    //bi-directional many-to-many association to ModPm
    @ManyToMany
    @JoinTable(name = "MOD_PM_SCOPE_TYPES",
            joinColumns = @JoinColumn(name = "SCOPE_TYPE_ID"),
            inverseJoinColumns = @JoinColumn(name = "PM_ID")
    )
    private List<ModPm> modPms;

是否可以从MOD_PM表中选择在SC_PE_TYPE_ID = 1的MOD_PM_SCOPE_TYPES表中有记录的实体?

本机SQL查询:

SELECT ID, NAME FROM MOD_PM WHERE ID IN (SELECT PM_ID FROM MOD_PM_SCOPE_TYPES WHERE SCOPE_TYPE_ID=1)

如何将此查询翻译为JPQL?

提问于
用户回答回答于

当您在查询中引用SCOPE_TYPE_ID时,您指的是什么?可能是ScopeType的ID或我没有看到的其他字段。我假设缺少范围类型id字段。

试试这个:

select p from ModPm p join p.modScopeTypes type where type.scopeTypeId = 1

扫码关注云+社区

领取腾讯云代金券