JPQL 多对多 select 查询

JPQL many to many select query

我有两个实体 class,存储库如下所示。我正在做 jpql select 查询。

Subscription.java

@Entity
@Table(name="Subscription")
public class Subscription implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="SubscriptionId", nullable=false)
    private Integer subscriptionId;

    @Column(name="BaseProductId", nullable=false)
    private Integer baseProductId;

    @ManyToMany(fetch = FetchType.LAZY, mappedBy="subscription")
    private List<Abc> abc;
}

Abc.java

@Entity
@Table(name="abc")
public class Abc implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="SubscriptionId", nullable=false)
    private Integer id;

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinColumn(name="id", referencedColumnName="BaseProductId", insertable = false, updatable = false, nullable = false)
    private List<Subscription> subscription;
}

AbcRepository.java

@Repository
public interface AbcRepository extends JpaRepository<Abc, Integer> {

    @Query(value="SELECT bpp FROM Abc bpp JOIN bpp.subscription s WHERE s.subscriptionId = ?1")
        public List<Abc> findBppm(Integer a);
    }
}

Select 查询生成:

select ... from abc bp_ inner join abc_subscription ... inner join Subscription subscripti2_ on ... where subscripti2_.SubscriptionId=?

... :- 这个地方有东西。

虽然我加入了 abc 和订阅,但在查询休眠中创建了一个由 _ 分隔的实体。即 abc_subscription.

知道我做错了什么吗?提前致谢。

@ManyToMany应该用在实体之间有linktable的场景。

如果未指定 @JoinTable,持久性提供程序使用的默认 link table 将是两个实体的串联,由“_”分隔。 最重要的是,f 未指定 link table 中假定的列名称将是实体 类.

上定义的 @Id 字段名称

尝试遵循规范并相应地调整您的情况:ManyToMany javadoc

通常,避免对多对多关系使用列表,因为这可能会在从任一实体中删除字段时导致问题。 而是使用 Sets private Set<> abc = new HashSet<>();