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