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

时间:2013-03-01 08:55:18

标签: java jpa collections many-to-many

我有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?

1 个答案:

答案 0 :(得分:18)

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

试试这个:

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