【问题标题】:Find by id=1 spring data jpa按 id=1 查找弹簧数据 jpa
【发布时间】:2019-10-24 22:27:21
【问题描述】:

我有一个表格组件和实体组件。我想从 jpa 查询中选择 id = 1 记录。我可以写“findByIdOne”或“findByIdEqualtoOne”吗?这会给我 id = 1 记录吗?请告诉我,谢谢。

【问题讨论】:

    标签: spring spring-data-jpa


    【解决方案1】:

    不,你不能。请参阅 Spring Data JPA 文档 documents 您可以使用的确切关键字。

    您可以随意specify 您希望方法执行的查询。类似的东西

    @Query("select c from Component c where c.id=1")
    Component findByIdOne();
    

    我必须声明:通过提供此解决方案,我假设您确实确定 ID 1 始终存在,并且在您可能正在运行应用程序的任何环境中始终指向完全相同的组件记录反对。我不推荐在您的应用程序代码中硬编码数据库 ID。

    【讨论】:

    • 谢谢@Gimby。该表中只有一条记录,最终可能会添加另一条记录。在任何时候,都只会有 2 条记录。 id 值在任何环境中都不会改变。感谢您的时间。
    【解决方案2】:

    直接编写查询 dsl 你不能,但是 Java 8 有一种使用默认方法的“方法”:

    假设您有以下查询:

    public interface ComponentRespository extends CrudRepository<Component, Long> {
    
        @Query("select c from Component c where c.id=:id")
        Component findById(@Param("id") Long id);
    
        default Component findByIdOne() {
            return findById(1L);
        }
        //eventually
        default Component findByIdTwo() {
            return findById(2L);
        }
    }
    

    这样你就可以使用了:

    private ComponentRespository componentRepository;
    
    .....
    Component componentOne = componentRepository.findByIdOne(); 
    Component componentTwo = componentRepository.findByIdTwo(); 
    

    【讨论】:

    • 嗨@vipul 看看这是不是你想要的。干杯
    • 将返回类型更改为可选时出错。可选。是否有机会仅使用实体类型作为返回,而不是 Optional
    • 我使用了可选的,就像一个魅力。谢谢@Brother。
    【解决方案3】:

    如果不是唯一的,您可以使用Optional&lt;EntityName&gt; findById(long id) 或List&lt;EntityName&gt; findById(long id)。

    【讨论】:

      【解决方案4】:

      如果不是唯一的,您可以使用 Optional&lt;EntityName&gt; findById(long id) 或 List&lt;EntityName&gt; findAllById。 我们有几种选择: findByIdIs(long id) 或 findByIdEquals(long id)

      【讨论】:

        猜你喜欢
        • 2017-11-07
        • 1970-01-01
        • 2015-05-26
        • 2017-01-03
        • 2015-10-29
        • 2017-07-06
        • 1970-01-01
        • 1970-01-01
        • 2016-06-02
        相关资源
        最近更新 更多