出于我的意图,org.springframework.data.repository.Repository
的JavaDoc对通用参数<T>
有点不精确。它说:
@ param存储库管理的域类型
好。
假设我们有这些实体:
@Entity
@Table
public class Parent {
@Id
private Long id;
@Getter
@OrderBy
@OneToMany(mappedBy = "parent")
private Set<Children> children;
}
@Entity
@Table
public class Children {
@Id
private Long id;
@OneToOne
@JoinColumn(name = "parent_id", nullable = false)
private Parent parent;
}
如果查询父母的所有孩子,那么哪个存储库是正确的?
public interface ParentRepository extends Repository<Parent, Long> {
// IntelliJ Warning: 'Children' domain type or valid projection interface expected here
@Query("SELECT children FROM Parent WHERE id = ?1")
List<Children> getChildrenByParentId(Long parentId);
}
public interface ChildrenRepository extends Repository<Children, Long> {
@Query("SELECT children FROM Parent WHERE id = ?1")
List<Children> getChildrenByParentId(Long parentId);
}
这个额外的查询呢?
@Query("SELECT parent.children FROM Parent parent LEFT JOIN parent.children children WHERE parent.id = ?1 ORDER BY children.id")
List<Children> getOrderedChildrenByParentId(Long parentId);
由于无论使用哪个存储库都可以正常工作,所以我更关注为什么ParentRepository
或ChildrenRepository
是正确的库。
浏览了文档之后:https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#reference,ParentRepository
似乎更正确-尽管是IntelliJ警告。
如果创建接口:
public interface ParentRepository extends Repository<Parent, Long>
参数Parent用于生成诸如findAll findOne之类的方法以返回正确的类型,而参数Long被用作主键类型。
如果您这样做:
@Query("SELECT parent.children FROM Parent parent LEFT JOIN parent.children children WHERE parent.id = ?1 ORDER BY children.id")
List<Children> getOrderedChildrenByParentId(Long parentId);
您完全可以自由使用您要使用的参数类型和返回类型。因此,将带有@Query批注的方法放在哪里都没有关系。