简体   繁体   中英

Spring JPA/Hibernate: use multiple projections on same query interface

this is a similar question of: this issue

I tried to use the same solution, but I have this error:

Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: from near line 1, column 9 [select from com.app.company.domain.organization.Organization as generatedAlias0 where generatedAlias0.deletedAt is null]

Look at the select statement: there is not any field requested!

Any idea?

Query in the Repository:

<T extends JPAProjection > List<T> findAllByDeletedAtIsNull(Class<? extends JPAProjection> projection);

Next, blank interface JPAProjection , and OrgId projection interface used to retrieve only id and name :

public interface JPAProjection {}

public interface OrgId extends JPAProjection {

    @Value("#{target.id}")
    Long getId();   

    @Value("#{target.name}")
    String getName();

}

And then, the call to the query:

return organizationRepository.findAllByDeletedAtIsNull(OrgId.class);

Thanks a lot, Andrea

If you want to use a single query method for several projections - all you need is Dynamic projections :

interface MyEntityRepo extends Repository<MyEntity, Long> {
  <T> T findById(Long id, Class<T> type);
}

Then you can use this method with projections and main entity as well:

MyEntity entity = findById(1L, MyEntity.class);
MyProjection entityProjection = findById(1L, MyProjection.class);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM