abs*_*hit 6 java spring spring-webflux spring-data-r2dbc r2dbc
我正在尝试在新的反应式数据 r2dbc 中复制我在 Spring Data JPA 中使用的一些功能。我知道 r2dbc 不是一个成熟的 ORM,但想了解在 r2dbc 中复制以下场景的最佳方法是什么:
public class Doctor extends BaseModel {
//other fields and id
@NotNull
@Enumerated(EnumType.STRING)
@ElementCollection(fetch = FetchType.LAZY, targetClass = Language.class)
@CollectionTable(name = "doctor_language",
joinColumns = @JoinColumn(name = "doctor_id"))
@Column(name = "language")
private List<Language> languages = new ArrayList<>();
@OneToMany(fetch = FetchType.LAZY, targetEntity = DoctorHealthProvider.class, mappedBy =
"doctor")
private List<DoctorHealthProvider> providers = new ArrayList<>();
// other fields
}
Run Code Online (Sandbox Code Playgroud)
如果我使用 Spring Data JPA,对 DoctorRepository(它扩展 JpaRepository)的一个简单的 findById 调用会给我一个doctor对象,其中包含表中的语言doctor_language列表和表中的健康提供者列表health_provider
我正在阅读有关预测的内容,但似乎无法找出在 Reactive Spring 中实现上述内容的最佳方法。任何帮助/指南/方向表示赞赏。
谢谢
您可以查看https://github.com/lecousin/lc-spring-data-r2dbc,但看起来尚未完全准备好使用。但如果您的需求不太复杂,它可能可以满足您的需求。
例如,您可以声明这样的链接:
@Table
public class TableWithForeignKey {
...
@ForeignKey(optional = false)
private LinkedTable myLink;
...
}
@Table
public class LinkedTable {
...
@ForeignTable(joinkey = "myLink")
private List<TableWithForeignKey> links;
...
}
Run Code Online (Sandbox Code Playgroud)
当您希望映射链接时,可以使用延迟加载或选择连接。
如果您使用 Spring 存储库的方法findBy...(findById、findAll...),则只会加载存储库的表。在这种情况下,您可以使用延迟加载。为此,您需要声明一个具有默认主体的方法,并且您的方法将自动实现:
public Flux<TableWithForeignKey> lazyGetLinks() {
return null; // will be implemented
}
Run Code Online (Sandbox Code Playgroud)
另一种方法是直接在请求中进行联接。目前不支持在存储库中自动执行联接(如 JPA 中的 @EntitiGraph),但您可以像这样实现您的方法:
public interface MyRepository extends LcR2dbcRepository<LinkedTable, Long> {
default Flux<LinkedTable> findAllAndJoin() {
SelectQuery.from(LinkedTable.class, "root") // SELECT FROM LinkedTable AS root
.join("root", "links", "link") // JOIN root.links AS link
.execute(getLcClient()); // execute the select and map entities
}
}
Run Code Online (Sandbox Code Playgroud)
结果将是所有 LinkedTable 实例,以及从数据库一起加载的链接列表。
| 归档时间: |
|
| 查看次数: |
1276 次 |
| 最近记录: |