Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data (JPA) - using generics in @Query

Tags:

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.

like image 954
saljuama Avatar asked Mar 27 '15 03:03

saljuama


People also ask

Is it possible to define a sort type in @query annotation using Spring JPA?

Spring Data JPA allows you to add a special Sort parameter to your query method. The Sort class is just a specification that provides sorting options for database queries. By using dynamic sorting, you can choose the sorting column and direction at runtime to sort the query results.

How can Spring Data JPA simplify your data access layer?

One of the core objectives of Spring Data JPA is to reduce your code and simplify your Data Access Layer, while still maintaining a rich and full-featured set of functionality. To make this possible, Spring DATA JPA allows you to build intelligent Spring Repository stereotyped interfaces.

What is the use of @query in JPA?

Understanding the @Query Annotation The @Query annotation can only be used to annotate repository interface methods. The call of the annotated methods will trigger the execution of the statement found in it, and their usage is pretty straightforward. The @Query annotation supports both native SQL and JPQL.

What is @query used for spring data?

Spring Data JPA @Query The @Query annotation declares finder queries directly on repository methods. While similar @NamedQuery is used on domain classes, Spring Data JPA @Query annotation is used on Repository interface. This frees the domain classes from persistence specific information, which is a good thing.


1 Answers

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

@Query("Select t.type from #{#entityName} t")
like image 142
manish Avatar answered Oct 01 '22 21:10

manish