繁体   English   中英

Spring 中 JPA Repository 接口投影的最佳实践?

[英]Best practices with interface projections for JPA Repository in Spring?

我想知道是否有人可以对我目前正在使用的模式提供反馈? 它涉及让一个实体实现一个 DTO 接口,该接口也在 JpaRepository 接口中使用(作为投影) - 对于同一实体 - 以返回具有特定列的查询结果。 DTO 接口还具有默认方法,以允许实体的任何实例和 DTO 代理具有类似的行为。

我希望回答的问题是这种模式是否有任何缺点,例如可能会阻止人们在生产中使用它的性能。 我也有兴趣了解其他人如何使用 JpaRepositories 查询特定数据字段。 下面我有一个代码示例,它说明了我正在使用的模式。

public interface InstructorDTO {
    String getFirstName();
    String getLastName();

    default String getFullName() {
        return getFirstName() + ' ' + getLastName();
    }
}

@Entity
public class Instructor implements InstructorDTO {
    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private int id;

    @Column(name="first_name")
    private String firstName;

    @Column(name="last_name")
    private String lastName;

    @Column(unique = true)
    private String email;

    @Override
    public String getFirstName() {
        return this.firstName;
    }

    @Override
    public String getLastName() {
        return this.lastName;
    }

    ...remaining getters and setters
}

@Repository
public interface InstructorRepository extends JpaRepository<Instructor, Integer> {

    <S> S findById(int id, Class<S> type);

    <T> Collection<T> findByEmail(String email, Class<T> type);
}


public class SomeClass {
    @Autowired
    InstructorRepository instructorRepository;

    public void someMethod {
        int id = 1;

        // Returns proxy
        InstructorDTO instructor1 = instructorRepository.findById(id, InstructorDTO.class);

        // Returns Instructor Object
        Instructor instructor2 = instructorRepository.findOne(id);

        System.out.println(instructor1.getFullName()); // returns John Doe
        System.out.println(instructor2.getFullName()); // returns John Doe
    }
}

相比之下,这种解决方案没有任何缺点。 如果您只需要几列,最好使用 DTO 而不是实体。

因为如果只在 SQL 语句上使用 DTO,则会生成用于选择数据的 SQL 语句。 如果您使用实体,可以加载急切或延迟获取的关系,这可能会导致 n+1 选择问题。

如果您真的希望您的实体扩展 DTO,这只是值得怀疑的。 这在我看来是没有意义的。

两个建议。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM