【问题标题】:How to do POJO projection in spring data jpa for native query如何在spring data jpa中进行POJO投影以进行本机查询
【发布时间】:2020-01-22 10:22:52
【问题描述】:

我有以下 MySQL 查询。我在 spring data jpa 中尝试过接口投影,但投影字段 id 是 UUID。所以它没有在界面投影中映射。所以我想尝试 POJO 投影,但它不起作用。

SELECT 
    f.receiver_user_id, f.modified_at, f.text
FROM
    (SELECT 
        receiver_user_id, MAX(modified_at) AS modified_at
    FROM
        text_log
    GROUP BY receiver_user_id) AS x
        INNER JOIN
    text_log AS f ON f.receiver_user_id = x.receiver_user_id
        AND f.modified_at = x.modified_at
ORDER BY f.modified_at DESC;

此外,如果建议对上述查询使用 JPA 标准构建器实现,将会很有帮助。

我已经尝试过遵循 Spring Data JPA 存储库查询实现

@Query(value = "SELECT " + 
            "f.receiver_user_id as receiverUserId, f.modified_at as modifiedAt, f.text as text" + 
            "FROM " + 
            "    (SELECT  " + 
            "        receiver_user_id, MAX(modified_at) AS modified_at " + 
            "    FROM " + 
            "        text_log " + 
            "    GROUP BY receiver_user_id) AS x " + 
            "        INNER JOIN " + 
            "    text_log AS f ON f.receiver_user_id = x.receiver_user_id " + 
            "        AND f.modified_at = x.modified_at " + 
            "ORDER BY f.modified_at DESC limit ?1  offset ?2 ", 
            nativeQuery = true)
    List<ITextLog> findTextLog(int l , int f);

    public interface ITextLog {

            public UUID getReceiverUserId();

            public Date getModifiedAt();

            public String getText();

    }

【问题讨论】:

  • 什么不起作用?此外,UUID 只是一个字符串,因此您可能希望使用字符串作为类型,而不是使用 UUID 类型。
  • 我也尝试过字符串,如果我使用字符串作为数据类型,那么它会在字符串中获取不正确的数据。
  • 请显示您尝试过的内容,目前只有一个查询。
  • @M.Deinum 更新问题。
  • 只有receiverUserId有问题吗?当您从 sql 和 ITextLog 中删除它时,它正在工作吗?

标签: mysql spring jpa spring-data-jpa


【解决方案1】:

基于这个答案:也许你可以使用this

@org.hibernate.annotations.Type(type="org.hibernate.type.UUIDCharType")
public UUID getReceiverUserId();

Or

@org.hibernate.annotations.Type(type="uuid-char")
public UUID getReceiverUserId();

【讨论】:

  • 我得到这个异常 java.lang.IllegalArgumentException: Projection type must be an interface!
猜你喜欢
  • 1970-01-01
  • 2020-02-11
  • 1970-01-01
  • 2018-12-16
  • 1970-01-01
  • 1970-01-01
  • 2021-06-01
  • 2022-07-11
  • 2023-01-14
相关资源
最近更新 更多