spring-data-jpa 通过JPA(提供者eclipselink)和Spring Data 使用列对来选择行

qco9c6ql  于 2022-11-10  发布在  Spring
关注(0)|答案(1)|浏览(147)

我在MSSQL中有一个如下所示的表-

create table t1 (

  id   int   IDENTITY(1,1),
  col1 int   not null,
  col2 int   not null, 

  constraint t1_UK UNIQUE (col1, col2)

)

和数据如下-

id    col1     col2
    1      25      661
    2      25      741
    3      89      661
    4      89      741

如何仅在col 1和col 2上使用where子句选择id为1和id为4的行?
实体定义-

@Entity
@Table
class T1Entity {
   @Id
   @GeneratedValue
   private int id;

   @Column
   private int col1;

   @Column
   private int col2;

   // getters, setters
}

注意,假设我有T1EntityRepository,我不能定义像findByCol1InAndCol2In(List.of(25, 89), List.of(661, 741)这样的方法,因为它将返回示例数据中的所有行。
我知道我需要像Select col1, col2 from t1 where (col1=25 and col2 = 661) OR (col1=89 and col2=741)这样的东西,但是如何使用JPA来实现这一点呢?(另外,在SQL本身中是否有一种方法可以不使用AND的OR)

fhg3lkii

fhg3lkii1#

我也遇到了同样的问题。我正在使用@Query编写自定义查询来解决这个问题。您可以编写自定义的Where causes,

@Query("SELECT wftr FROM WorkflowActivityRequestEntity wftr WHERE wftr.status IN :status")
List<WorkflowActivityRequestEntity> findWorkflowActivityRequestsByStatus(
        @Param("status")
        List<String> status);

@Query("SELECT wftr FROM WorkflowActivityRequestEntity wftr WHERE wftr.owner NOT IN :owners")
List<WorkflowActivityRequestEntity> findWorkflowActivityRequestsNotOwnedBy(
        @Param("owners")
        List<String> owners);

对于AND和OR组合,您还可以使用JpaSpecificationExecutor扩展存储库接口
然后使用Criteria Builder。我在项目中执行此操作时引用了https://www.baeldung.com/spring-data-criteria-queries
希望能有所帮助。

相关问题