【问题标题】:Database unique keys, JPA repositories and getByUniqueKey signatures: how does it works?数据库唯一密钥、JPA 存储库和 getByUniqueKey 签名:它是如何工作的?
【发布时间】:2012-09-21 07:33:24
【问题描述】:

背景

数据表item:

+---------+---------+--------+
|  field  |  type   | index  |
+---------+---------+--------+
| id_item | INT     | PK     |
| name    | VARCHAR | UNIQUE |
+---------+---------+--------+

ItemRepository.java:

public interface ItemRepository extends CustomRepository<Item, Integer> {
    public Item getByName(String name); // because of the unique index
}

CustomRepository.java:

@NoRepositoryBean
public interface CustomRepository<E, PK extends Serializable> extends PagingAndSortingRepository<E, PK>, JpaSpecificationExecutor<E> {
    // common methods
}

CustomRepositoryImpl.java:

public class CustomRepositoryImpl<E, PK extends Serializable> extends SimpleJpaRepository<E, PK> implements CustomRepository<E, PK> {
    // common methods implementations
}

问题

如您所见,接口ItemRepository 没有实现。这意味着,getByName 方法只有一个签名,永远不会在任何地方实现。但它有效。怎么样?

附言

对于持怀疑态度的人,使用 Eclipse,当按住 Ctrl 并将鼠标悬停在 getByName 签名上时,单击 Open Implementation 根本不会打开任何 JAVA 文件。

【问题讨论】:

    标签: java spring jpa repository unique-index


    【解决方案1】:

    Spring 将 AOP 用于存储库,并将拦截 getByX 与 bean 属性匹配的任何 X 方法。在您的示例中,Item bean 声明了 name 属性,因此 Spring 会为您拦截它。

    请参阅 Spring Data JPA 手册中的 Defining query methods

    【讨论】:

    • 谢谢。它似乎也适用于findByX 而不是getByX
    • 是的:findByfindreadByreadgetByget 一切正常。
    猜你喜欢
    • 2018-05-24
    • 2011-03-12
    • 1970-01-01
    • 2016-12-15
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多