1

我想知道是否有人可以就我目前正在玩的模式提供反馈?它涉及让实体实现 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
    }
}
4

1 回答 1

1

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

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

仅当您真的希望您的实体扩展 DTO 时才值得怀疑。在我看来,这没有意义。

两个建议。

于 2018-09-18T07:04:06.897 回答