【发布时间】:2022-01-18 01:54:52
【问题描述】:
给定表模式如下(这是mysql语法,但没关系)
-- base table keeping all subscription data
CREATE TABLE user_subscription (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
user_id INTEGER NOT NULL,
data VARCHAR(2000) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
-- supportive view focusing on every user's latest row
CREATE VIEW user_subscription_latest AS
SELECT s1.*
FROM user_subscription s1
LEFT JOIN user_subscription s2
ON s2.user_id = s1.user_id AND s2.updated_at > s1.updated_at
WHERE s2.id IS NULL;
我有以下基表的实体类user_subscription
import javax.persistence.*;
@Entity
@Table(name = "user_subscription")
public class UserSubscription implements java.io.Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false, updatable = false, insertable = false)
private Integer id;
@Column(name = "user_id", nullable = false)
private Integer userId;
@Column(name = "data", nullable = true, length = 2000)
private String data;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "created_at", nullable = false, updatable = false, insertable = false)
private java.time.LocalDateTime createdAt;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "updated_at", nullable = false, updatable = false, insertable = false)
private java.time.LocalDateTime updatedAt;
}
并遵循 Spring Data JPA 存储库(仍然没关系。它可以是任何 JPA 场景)
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
public interface UserSubscriptionRepository extends JpaRepository<UserSubscription, Integer> {
// TODO How can I achieve this without using nativeQuery?
@Query(value = "SELECT * FROM user_subscription_latest", nativeQuery = true)
java.util.List<UserSubscription> findLatest();
}
由于视图user_subscription_latest 是user_subscription 的子集,它们可以互换,但我不知道如何将它们组合在一起。
我的问题是设计 JPA 实体的正确/首选方法是什么,以便我可以在查询时利用支持视图 user_subscription_latest,同时保持对基表 user_subscription 的可访问性,而无需 nativeQuery?
【问题讨论】: