2

So I have three entities. A FormCollection contains multiple Form. The Form is created from a template and thus has also a many-to-one relation to FormTemplate.

@Table(name = "form_collection", schema = "public")
public class FormCollectionDO extends BaseAuditableDO {
    @OneToMany(mappedBy = "formCollection")
    @OrderBy("formTemplate.templateId") //throws error
    private List<FormDO> forms = new ArrayList<>();
}

@Table(name = "form", schema = "public")
public class FormDO extends BaseAuditableDO {

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "form_template_id")
    private FormTemplateDO formTemplate;
}

@Table(name = "form_template", schema = "public")
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class FormTemplateDO extends BaseDO {

    @Column(name = "template_id", nullable = false)
    @NotNull
    private Long templateId;
}

@OrderBy("formTemplate.templateId") throws an error:

o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: missing FROM-clause entry for table "formtemplate"

@OrderBy("formTemplate.id") works fine. The id comes from the abstract class BaseDO. Why does it not work with any of the fields from the FormTemplateDO class?

simibac
  • 7,672
  • 3
  • 36
  • 48
  • form_template and formTemplate aren't the same, which one do you need? – Frank Heikens Dec 11 '20 at 14:50
  • For my understanding `form_template` is on DB level while `formTemplate` is on Java level. If I use `@OrderBy("form_template.template_id")` I get the same error. – simibac Dec 11 '20 at 15:56
  • I get auto-complete with `formTemplate.templateId` in IntelliJ. Also, since it works with `formTemplate.id`, I guess I need `fromTemplate`. – simibac Dec 11 '20 at 15:59

2 Answers2

0

Although I am not sure about this solution, What I am suspecting is this issue happens because the formTemplate.templateId isnt part of your query indeed.

I see you are using @OneToMany for defining the relationship, but in hibernate, the default FetchMode is SELECT which means your order by parameter isnt part of your query. To make this parameter part of your query, you will have to make a Join query.

Try this out -

@Fetch(value = FetchMode.JOIN) 
@OneToMany(mappedBy = "formCollection")
@OrderBy("formTemplate.templateId") //throws error
private List<FormDO> forms = new ArrayList<>();

And propogate this join to further levels. It might solve your problem.

Anand Vaidya
  • 1,374
  • 11
  • 26
0

When you want to order by a collection of entities by a nested attribute, you can not use @OrderBy, because the nested attribute is not part of your query. You can only use @OrderBy for of first level attribute OR a nested attribute IF it is a collection of @Embeddable.

So for this case, you have to use @SortNatural or @SortComparator.

Flyout91
  • 782
  • 10
  • 31