We are using JPA2, Spring Data and QueryDSL in our project. I have the following tables and related JPA entities:
table Person (id, ...) 
table Activity (id, type, ...)
@Entity
@Configurable
public class Activity {
   @ElementCollection
   @CollectionTable(joinColumns = @JoinColumn(name = "ACTIVITY_ID"))
   @NotEmpty
   @Valid
   private Set<ActivityName> names = new HashSet<>();
table ActivityName(activity_id, name, ...) 
@Embeddable
  @Immutable
  @Table(uniqueConstraints = @UniqueConstraint(columnNames = "NAME"))
  public static class ActivityName { ... }
table ActivityLevel(person_id, activity_id, level) 
@Entity
@Immutable
@Validated
public final class ActivityLevel{...}
1..n for Actitivy to ActivityName - an activity might have different names (e.g. running, jogging)
A person might have a certain level for a given activity and can perfom several activities (each with a defined level).
Example the following data:
Searching for persons who are "running" or "dancing" should get a result like this:
Person[Name]   ActitiyName  ActivityLevel ActitiyName  ActivityLevel  Sum
Bob             running         0.7         dancing         0.1       0.8
Mary            running         0.5                                   0.5          
My Question: Is there a JPA QL / QueryDSL way to get such a result with one expression / projection? What I already have is a multi-step solution - selecting activity names and levels, performing the grouping and sum with Java8. If I do the grouping with querydsl, I do not get the single level entries. Vice versa, in my solution I have to perform several other steps.
Would be nice to know if this is possible just by using a query.
Pure JPA & QueryDsl works only with entities. So you could make a db view that aggregates the data you're looking for and map it to a new entity, which you can simply query.
Another solution is to use QueryDsl's native jpa query support. See http://www.querydsl.com/static/querydsl/3.6.1/reference/html/ch02.html bottom half. You would need the lowest paragraph (Query and project into DTO).
It boils down to:
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