spring数据:使用附加字段获取计数

juud5qan  于 2021-07-16  发布在  Java
关注(0)|答案(2)|浏览(265)

我想返回一个字段加上另一个字段的计数。但我不能把它变成pojo。我只能把它作为对象数组的列表。我有什么:

public interface ChatMessageRepository extends JpaRepository<ChatMessage, Long> {

    @Query(value = "select count(c.is_read), c.chat_id from chat_message c where (c.sender_id = :userId or c.receiver_id = :userId) group by c.chat_id", nativeQuery = true)
    List<Object[]> findAllByUserId(long userId);

但我需要这样的东西:

@Query(value = "select count(c.is_read), c.chat_id from chat_message c where (c.sender_id = :userId or c.receiver_id = :userId) group by c.chat_id", nativeQuery = true)
List<POJO> findAllByUserId(long userId);

@Data
public static class POJO {
    private long count;
    private long id;
}
inb24sb2

inb24sb21#

找到了答案:

public interface POJO {
    Long getCount();
    Long getId();
}

   @Query(value = "select count(c.isRead) as count,c.chat.chatId as id from ChatMessage c where (c.senderId = :userId or c.receiverId= :userId) group by c.chat.chatId ")
    List<POJO> findAllByUserId(long userId);
krugob8w

krugob8w2#

你可以用

long countByUserId(long userId);

更多信息https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.core-概念检查示例5

相关问题