2

我正在尝试在 java 接口中继承以下参数(来自 Spring Data JPA 的示例,但问题通常是关于注释的参数):

public interface ItemRepository<T extends Item> extends BaseRepository<T> {

    public final String type = null;



    @Query("select distinct i from " + type + " i " +
            "join i.tags t " +
            "join fetch i.locale where t = ?1")
    public List<T> findByTag(Tag t);
}

这样在继承的接口中我就可以:

public interface EventRepository extends ItemRepository<Event> {

    public final static String type = "Event";
}

但不幸的是,变量“type”的字符串值关联到变量的时间太晚了,所以在创建注解时,该值仍然为空。我可以强制编译器关联子接口中的变量吗?

谢谢

4

3 回答 3

1

我不是 Java 专家,但我认为您不能这样做。家长班对孩子一无所知。但是,您可以执行以下操作:

public interface ItemRepository<T extends Item> extends BaseRepository<T> {

    public final String type = null;

    public static final String QUERY_PART1 = "select distinct i from ";
    public static final String QUERY_PART2 = " i " + 
            "join i.tags t " +
            "join fetch i.locale where t = ?1";
    public List<T> findByTag(Tag t);
}  

public interface EventRepository extends ItemRepository<Event> {

    public final static String type = "Event";

     @Query(QUERY_PART1 + type + QUERY_PART2)
}
于 2012-02-13T22:25:24.557 回答
1

简而言之,没有。您不能强制编译器“将变量与子接口关联”。

Java 编译器需要能够在编译时确定所有注释值。它需要写出到类文件中,以便ItemRepository将常量值放入@Query注释中。您认为这对您的代码来说是什么常数值?

碰巧的是,编译器可以在编译时从您的代码中确定此注释的值。但是,它并不完全是您想要的值。(我假设你不小心从字段中省略了static修饰符- 我相信你的代码不会编译,如果你用方法替换你的字段,它也不会编译。)typeItemRepositorytypegetType()

您的代码看起来可以在编译时确定子接口的注释值。问题是无法在编译时确定 superinterface 的注释值ItemRepository

于 2012-02-13T23:06:12.087 回答
0

最后,我对行为和不灵活感到非常不满,所以我给自己写了一个小工具。使用示例如下:

https://github.com/knyttl/Maite/wiki/Maite-Persistence

有两个子类和定义功能的父类。但诀窍在于构建查询的流畅界面。你怎么看?

于 2012-02-15T22:52:20.573 回答