sal*_*ama 12 generics spring-data-jpa
我想知道是否可以在spring数据的命名查询中使用泛型(我自己使用jpa),是否可以做这样的事情?
@NoRepositoryBean
public interface EnumerationRepository<T extends Enumeration> extends JpaRepository<T,Integer> {
@Query("Select t.type from T t")
public List<String> selectTypes();
}
Run Code Online (Sandbox Code Playgroud)
枚举类就是这个
@MappedSuperclass
public abstract class Enumeration {
@Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id", length = 3)
private int id;
@Column(name = "type", nullable = false, unique = true, length = 30)
private String type;
// getters / setters .. etc
}
Run Code Online (Sandbox Code Playgroud)
为简单起见,我在Enumeration类中省略了一些字段.
试过这个,但很明显它抱怨导致类T没有映射.
关键是因为我有20多个表共享一些基本结构,并且因为我需要查询只从列中提取数据,而不是整个实体,所以很高兴找到一种方法来获取"父"存储库中的查询而且不必复制代码20次以上.
man*_*ish 22
如果使用Spring Data JPA 1.4或更高版本,以下内容将起作用:
@Query("Select t.type from #{#entityName} t")
Run Code Online (Sandbox Code Playgroud)