[基于意见]:做什么更好?编写我们自己的联接查询还是使用 JPA 的联接? [已关闭]

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

我正在使用 Springboot 构建 REST API。我现在很困惑。 Springboot为我们提供了一种直接使用JOINS的方法,使用这样的模型 -

public class Conversation {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long conversation_id;

    @ManyToOne
    @JoinColumn(name = "profile_id_one")
    private Profile profile;

    @ManyToOne
    @JoinColumn(name = "profile_id_two")
    private Profile profile2;


    @OneToMany(mappedBy = "conversation")
    private List<DirectMessage> directMessages;
}

正如你所看到的,我们可以使用注释来定义 Springboot 中的关系或连接。 但我不想使用这些。这些对我来说似乎是魔盒,我不知道它们在后台如何工作,它只是给我输出。

现在我也有这个选项,我经常使用 -

    @Query("SELECT new com.discwords.discwords.model.Profile(CAST(IF(profile_id1 = :profile_id, profile_id2, profile_id1) AS Long), user_id, username, email, picture_url) FROM FriendList JOIN Profile p ON p.profile_id = CAST(IF(profile_id1 = :profile_id, profile_id2, profile_id1) AS Long) WHERE :profile_id IN (profile_id1, profile_id2)")
    List<Profile> findFriends(@Param("profile_id") long profile_id);

只是我必须使用单独的 DTO 并且必须使用构造函数映射。但我确实知道它是如何工作的以及我正在发送什么查询。

请指导我,我应该使用哪种方法?

java spring-boot
1个回答
-3
投票

您知道正确的答案,因为您陈述了不使用 JPA 的主要原因:

这些对我来说似乎是神奇的盒子,我不知道它们是如何在后台工作的,它只是给我输出。

相信你的直觉。 :)

根据 20 多年的软件工程师经验,我的观点是编写自己的查询。 这是我的理由:

  • 在将每个查询粘贴到代码中之前,您必须首先编写并测试每个查询,这样您就可以确切地知道要得到什么
  • 后续开发人员可以准确地看到您的意图,并能够直接运行您的查询。当您返回自己的代码并且不记得第一次编写代码时的想法时,这也很有帮助。

我当前的项目使用 MongoDB 和 MongoDB Java 驱动程序(Spring 但不是 Spring Boot,没有 JPA)。出于上述第二个原因,我们仍然将每个查询作为注释粘贴到代码中。

我们自己处理持久性是一件小事,但准确了解如何与数据库交互是非常值得的,特别是在复杂查询或出现问题时。

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