英文:
Spring JPA data, multiple methods with same functionality
问题
我正在使用Spring Data JPA与数据库交互,但是我遇到了一个问题:我不能用不同的命名实体多次定义相同的方法。
考虑以下代码:
class Repository {
@EntityGraph(value = UserEo.FULL, type = EntityGraph.EntityGraphType.LOAD)
public Optional<UserEo> findUserEoByEmail/*Full*/(String email);
@EntityGraph(value = UserEo.BRIEF, type = EntityGraph.EntityGraphType.LOAD)
public Optional<UserEo> findUserEoByEmail/*Brief*/(String email);
}
我希望能够拥有不同命名图的单独方法,但是在方法名称后添加附加信息会导致Spring出错。如何解决这个问题?
英文:
I am using spring data jpa to interact with a database, however I've come across a problem: I can't define the same method multiple times with different named entities.
Consider:
class Repository {
@EntityGraph(value = UserEo.FULL, type = EntityGraph.EntityGraphType.LOAD)
public Optional<UserEo> findUserEoByEmail/*Full*/(String email);
@EntityGraph(value = UserEo.BRIEF, type = EntityGraph.EntityGraphType.LOAD)
public Optional<UserEo> findUserEoByEmail/*Brief*/(String email);
}
I'd like to have separate methods with different named graphs, but adding additional information to the name of the methods breaks spring. How can this be solved?
答案1
得分: 7
正如注释所示,正确命名方法将不会“破坏Spring”。你可以这样做:
public interface Repository extends JpaRepository<UserEo, Long> {
@EntityGraph(value = UserEo.FULL, type = EntityGraph.EntityGraphType.LOAD)
public Optional<UserEo> findFullByEmail(String email);
@EntityGraph(value = UserEo.BRIEF, type = EntityGraph.EntityGraphType.LOAD)
public Optional<UserEo> findBriefByEmail(String email);
}
或者你可能想要将内容分割到两个不同的仓库中,如下所示:
public interface RepositoryFull extends JpaRepository<UserEo, Long> {
@EntityGraph(value = UserEo.FULL, type = EntityGraph.EntityGraphType.LOAD)
public Optional<UserEo> findByEmail(String email);
}
以及
public interface RepositoryBrief extends JpaRepository<UserEo, Long> {
@EntityGraph(value = UserEo.BRIEF, type = EntityGraph.EntityGraphType.LOAD)
public Optional<UserEo> findByEmail(String email);
}
英文:
As comment suggests naming the methods correctly will not "break Spring". You can have:
public interface Repository extends JpaRepository<UserEo, Long> {
@EntityGraph(value = UserEo.FULL, type = EntityGraph.EntityGraphType.LOAD)
public Optional<UserEo> findFullByEmail(String email);
@EntityGraph(value = UserEo.BRIEF, type = EntityGraph.EntityGraphType.LOAD)
public Optional<UserEo> findBriefByEmail(String email);
}
Or maybe you want to break stuff in two repositories, like:
public interface RepositoryFull extends JpaRepository<UserEo, Long> {
@EntityGraph(value = UserEo.FULL, type = EntityGraph.EntityGraphType.LOAD)
public Optional<UserEo> findByEmail(String email);
}
and
public interface RepositoryBrief extends JpaRepository<UserEo, Long> {
@EntityGraph(value = UserEo.BRIEF, type = EntityGraph.EntityGraphType.LOAD)
public Optional<UserEo> findByEmail(String email);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论