首页 > 解决方案 > 如何将 FindAllBy 与 JpaRepository 中的多个字段一起使用?

问题描述

您可以在下面找到一个显示我的问题的最小示例:

src/main/kotlin/com/mytest/findallbytest/Application.kt

package com.mytest.findallbytest

import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication

@SpringBootApplication
class MyTestApplication

fun main(args: Array<String>) {
    runApplication<MyTestApplication>(*args)
}

src/main/kotlin/com/mytest/findallbytest/model/Thing.kt

package com.mytest.findallbytest.model

import org.springframework.data.jpa.domain.AbstractPersistable
import javax.persistence.Entity
import javax.persistence.Table

@Entity
@Table(name = "things")
class Thing(
        val foo: Long,
        val bar: Long
) : AbstractPersistable<Long>()

src/main/kotlin/com/mytest/findallbytest/repository/ThingRepository.kt

package com.mytest.findallbytest.repository

import com.mytest.findallbytest.model.Thing
import org.springframework.data.jpa.repository.JpaRepository

interface ThingRepository : JpaRepository<Thing, Long> {
    fun findAllByFooAndBar(foos: Iterable<Long>, bars: Iterable<Long>): Iterable<Thing>
}

src/main/resources/application.yml

spring:
  datasource:
    url: jdbc:h2:mem:db;MODE=PostgreSQL

src/main/resources/db/migration/V1__things.sql

CREATE SEQUENCE HIBERNATE_SEQUENCE;

CREATE TABLE things (
    id      BIGINT PRIMARY KEY NOT NULL,
    foo     BIGINT NOT NULL,
    bar     BIGINT NOT NULL
);

src/test/kotlin/com/mytest/findallbytest/FullTest.kt

package com.mytest.findallbytest

import com.mytest.findallbytest.model.Thing
import com.mytest.findallbytest.repository.ThingRepository
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.junit.jupiter.SpringExtension

@ExtendWith(SpringExtension::class)
@SpringBootTest
class FullTest {

    @Autowired
    lateinit var repo: ThingRepository

    @Test
    fun `basic entity checks`() {
        repo.save(Thing(1, 2))
        repo.save(Thing(3, 4))
        repo.save(Thing(1, 4))
        assertThat(repo.findAll()).hasSize(3)

        // ERROR: Expected size:<2> but was:<0>
        assertThat(repo.findAllByFooAndBar(listOf(1L, 3L), listOf(2L, 4L))).hasSize(2)
    }
}

问题是,findAllByFooAndBar返回一个空列表。但是我希望它返回三个已保存实体中的前两个。

我做错了什么,我的目标或查询多个实体,匹配多个字段,如何实现?

标签: hibernatespring-bootjpakotlinspring-data-jpa

解决方案


fun findAllByFooInAndBarIn(foos: Iterable<Long>, bars: Iterable<Long>): Iterable<Thing>

推荐阅读