hibernate - 如何将 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
返回一个空列表。但是我希望它返回三个已保存实体中的前两个。
我做错了什么,我的目标或查询多个实体,匹配多个字段,如何实现?
解决方案
fun findAllByFooInAndBarIn(foos: Iterable<Long>, bars: Iterable<Long>): Iterable<Thing>
推荐阅读
- reactjs - 春季启动时出现Cors错误,将其与反应连接并尝试部署在tomcat或jboss服务器上?
- javascript - 如何在styles.js中更改禁用按钮的颜色
- c# - 没有键为“Conve”的“IEnumerable”类型的 ViewData 项
- django - django 媒体图片网址未显示
- python - 怎么做船拍?
- okta - Okta 小部件和 MFA 的部分登录问题
- python - Python:如何使用 Matplotlib 将文本垂直放置在条形图中
- c - C、wait()返回什么进程?
- python-3.x - 无法从歌词提取器导入 SongLyrics
- linux - hidepid=2 更新后停止工作。内核不支持“每个挂载点”?