【问题标题】:Spring jpa doesn't return the correct record for findFirstById_OrderByCreationDate_DescSpring jpa 没有为 findFirstById_OrderByCreationDate_Desc 返回正确的记录
【发布时间】:2020-03-10 19:36:14
【问题描述】:

我的测试中有一个非常愚蠢的问题。我正在使用@DataJpaTest 在一个简单的存储库上运行一些简单的测试。我有一个名为 Event 的实体和一个应该始终返回最后一个条目的存储库接口。

但是,无论我做什么,我都会得到第一个条目。

@Entity
@Cacheable(false)
public class Event {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne(optional = false)
    private Observed observed;

    private LocalDateTime creationDate;

    //Constructor that sets the observer and timestamp
    //getters and setters

}

我通过 JPA 查询:

public interface EventRepository extends JpaRepository<Event, Long> {

    Event findFirstById_OrderByCreationDate_Desc(@Nonnull Long id);

}

现在我希望这段代码能够执行以下操作。按事件的创建日期对事件进行排序,其中包含精确到毫秒的时间戳,将最后一个放在顶部,然后仅返回最后一个作为事件的结果。这似乎在实际应用程序中起作用。但在测试中,会发生以下情况。

@Test
public void createAndFindLastEvent() {
    Event event1 = new Event(observer);
    eventRepository.save(event1);
    Event event2 = new Event(observer);
    eventRepository.save(event2);
    Event event3 = eventRepository.findFirstById_OrderByCreationDate_Desc(observer.getId());
}

结果是event3 包含event1 的值,即使event2 具有较晚的时间戳。这让我很生气。我尝试在保存时使用saveAndFlush(),直接在存储库上使用flush(),并将@Cacheable(false) 放在实体类本身上,以确保不会发生奇怪的事情。我错过了什么吗?这不应该像我期望的那样工作吗?

最奇怪的部分是findAll() 确实返回了两个事件,而排序 ASC 或 DESC 似乎没有任何改变。

【问题讨论】:

    标签: spring spring-boot spring-data-jpa spring-data


    【解决方案1】:

    尝试改变

    Event findFirstById_OrderByCreationDate_Desc(@Nonnull Long id);
    

    Event findFirstByObserved_IdOrderByCreationDateDesc(@Nonnull Long id);
    

    没有下划线也应该可以工作

    Event findFirstByObservedIdOrderByCreationDateDesc(@Nonnull Long id);
    

    另见: 4.4.3. Property Expressions和文章:SpringData: Property Traversal

    您的查询似乎是在询问EventId。 下划线似乎没有必要,因为不应该有歧义:如果您有的话,它们会很有用,例如Event 中的observedId 属性。在第一个选项 (...Observed_Id...) 中使用下划线可以解决该潜在问题。

    我有 checked the sql queries 并且使用下划线没有区别。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-10
      • 1970-01-01
      • 2018-02-26
      • 2016-10-31
      • 1970-01-01
      • 2018-12-13
      • 1970-01-01
      相关资源
      最近更新 更多