Spring Data (JPA) - using generics in @Query

隐身守侯 提交于 2020-05-26 10:20:51

问题


I wonder if it's possible to use generics in the named queries in spring data (using jpa myself), is it possible to do anything like this?

@NoRepositoryBean
public interface EnumerationRepository<T extends Enumeration> extends JpaRepository<T,Integer> {
  @Query("Select t.type from T t")
  public List<String> selectTypes();
}

Enumeration class being this

@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 
}

I ommitted some fields in the Enumeration class for the sake of simplicity.

Tried this but obviously it complains cause class T is not mapped.

The point is because i have like 20+ tables that share some basic structure, and since i need queries to extract only data from columns, not the whole entity, would be nice to find a way to get the query in the "parent" repository and not having to replicate the code 20+ times.


回答1:


If using Spring Data JPA 1.4 or higher, the following will work:

@Query("Select t.type from #{#entityName} t")


来源:https://stackoverflow.com/questions/29292963/spring-data-jpa-using-generics-in-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!