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.
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.
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.
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.
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.
If using Spring Data JPA 1.4 or higher, the following will work:
@Query("Select t.type from #{#entityName} t")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With