0

I am using the an entity that has multiple properties/table columns:

@Entity
public class History {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @NotNull
    @Column
    ZonedDateTime dateCreated;

    @NotNull
    @Column
    private ZonedDateTime dateValidFrom;

    ...

and I have a Spring MVC controller with a handler that returns such History entries sorted by a particular property (e.g. dateValidFrom). The code below is from the HistoryService:

public List<History> findAll(int page, int pageSize) {
    PageRequest pageSettings = PageRequest.of(page, pageSize, Sort.by(Sort.Direction.ASC, "dateValidFrom"));
    return historyRepo.findAll(pageSettings).stream().collect(Collectors.toList());
}

How can I avoid using the hardcoded dateValidFrom property name and have a type-safe construct (detecting renaming mistakes at compile-time)?

Gabriel Petrovay
  • 20,476
  • 22
  • 97
  • 168

1 Answers1

0

JPA 2 defines a typesafe Criteria API which allows Criteria queries to be constructed in a strongly-typed manner, utilizing so called static metamodel classes. see: JPA Static Model Generator

These models are static classes that allows you to: _History.dateValidFrom which returns a string of the field name, thus avoiding hardcoded strings.

Check this answer for how to generate those static models:

SaleemKhair
  • 499
  • 3
  • 12