Spring 使用复合键获取实体上的数据页
我有一个实体,它通过使用Spring 使用复合键获取实体上的数据页,spring,hibernate,Spring,Hibernate,我有一个实体,它通过使用@IdClass,定义了一个复合主键,但是当我试图从这个表中获取一页数据时,我得到了一个语法错误(MSSQL) 实体 @IdClass(HoldCustodian.HoldCustodianKey.class) public class HoldCustodian implements Serializable { @Version private Long lockCount; @Id @ManyToOne(optional =
@IdClass
,定义了一个复合主键,但是当我试图从这个表中获取一页数据时,我得到了一个语法错误(MSSQL)
实体
@IdClass(HoldCustodian.HoldCustodianKey.class)
public class HoldCustodian implements Serializable {
@Version
private Long lockCount;
@Id
@ManyToOne(optional = false)
private Hold hold;
@Id
@ManyToOne(optional = false)
private User user;
// ETC
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
public static class HoldCustodianKey implements Serializable {
private Long hold;
private Long user;
}
储存库
public interface HoldCustodianRepository extends JpaRepository<HoldCustodian, HoldCustodian.HoldCustodianKey>, JpaSpecificationExecutor<HoldCustodian> {}
你知道我哪里出错了吗?我要么需要
选择COUNT(*)
,要么我的映射不正确?我认为@EmbeddedId
和@MapsId
的组合在您的情况下会更好地工作,这样就可以从实体中访问原始主键(Long-s)及其对应的实体(Hold和User)。它还将简化标准的创建(看到您的存储库是JpaSpecificationExecutor
)。另外,不要忘记将您的存储库从JpaRepository
更改为paging和sortingrepository
。谢谢-事实证明,主要问题是在生成的查询中使用了distinct
,使用count查询时,使用PK而不仅仅是count(*)
!对于我使用此实体,不需要distinct。至于JPARepository
-由于未列出查询,我可以正确使用。
select distinct count(distinct holdcustod0_.hold_sid, holdcustod0_.user_sid) as col_0_0_ from sec.HoldCustodian holdcustod0_ inner join sec.Hold hold1_ on holdcustod0_.hold_sid=hold1_.sid where hold1_.sid=2
SQL Error: 102, SQLState: S0001
2021-05-25 15:38:34.577 ERROR 10 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : Incorrect syntax near ','.
2021-05-25 15:38:34.585 ERROR 10 --- [nio-8080-exec-2] c.i.b.v.ValidationExceptionHandler : Data layer exception: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
2021-05-25 15:38:34.586 ERROR 10 --- [nio-8080-exec-2]