如何根据限制子句将 OneToMany 关系映射到 OneToOne?

问题描述 投票:0回答:1

我有两个 JPA 实体:

@Entity
@Table(name = "account")
data class Account(

    @Id
    @Column(name = "uuid")
    var uuid: UUID,

    @Column(name = "email")
    val email: String,

    @GeneratedValue
    @Column(name = "created")
    val created: DateTime = DateTime.now(),

    @GeneratedValue
    @Column(name = "modified")
    val modified: DateTime = DateTime.now(),

    @OneToMany(mappedBy = "account", fetch = FetchType.EAGER)
    val connectionStates: List<AccountConnectionState> = mutableListOf(),
) {

    fun getCurrentConnectionState(): AccountConnectionState? {
        return connectionStates.maxByOrNull { it.modified }
    }
}

@Entity
@Table(name = "account_connection_state")
data class AccountConnectionState(

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    var id: Long? = null,

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "account_uuid", nullable = false)
    val account: Account,

    @Column(name = "connection_status")
    val connectionStatus: String,

    @Column(name = "created")
    val created: DateTime = DateTime.now(),

    @GeneratedValue
    @Column(name = "modified")
    val modified: DateTime = DateTime.now(),
)

我希望在

Account
上有一个名为
connectionState
的字段,它根据
AccountConnectionState
日期列映射到最新的
modified

在上面,我仅使用一个基于

@OneToMany
关系中的整个列表的函数来完成此操作。有没有办法将其映射到 JPA 中的单个值,而不加载
connectionStates
关系类型中的
@OneToOne
的整个列表?

在 MySQL 中我会使用:

SELECT * FROM account a
JOIN (
    SELECT * FROM account_connection_state acs
    ORDER BY acs.modified DESC limit 1
) inn ON inn.account_uuid = a.uuid;
spring hibernate kotlin jpa spring-data-jpa
1个回答
0
投票

在找到更好的解决方案之前,您可以使用类似 如何在 OneToMany 关系中仅检索一条记录? .

引入一个新字段(例如

boolean active
),然后用
connectionStates
中的
@SQLRestriction("active is true")
注释
org.hibernate.annotations
(这替换了链接问题中已弃用的
@Where
)。然后查询将包含
...and (xxx.latest is true)

© www.soinside.com 2019 - 2024. All rights reserved.