Spring Data (JPA) - using generics in @Query

2020-08-09 07:19发布

问题:

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")