1

In our project, we have an entity class Employee, that looks something like this:

@Entity
class Employee {
  ...
  long travelDistanceAndTimeId;
  ...
}

We now want to use Spring Data JPA in order to find all employees that have a certain travelDistanceAndTimeId, so our EmployeeRepository looks like this:

interface EmployeeRepository extends Repository<Employee, Long> {

  List<Employee> findByTravelDistanceAndTimeId(long travelDistanceAndTimeId);
}

However, this fails, since Spring Data JPA thinks this method should look for an employee that has a given travelDistance and a given timeId, because as per the Spring Data JPA documentation, the and is treated as a method predicate keyword here.

Is there a way to make Spring Data JPA treat the travelDistanceAndTimeId as one field, and disable the "AND" method keyword for this query?

tuesday
  • 582
  • 1
  • 7
  • 14
  • What is your field `travelDistanceAndTimeId` ? How can you save the 'travelDistance' AND 'TimeId' in one Long field? I would expect 2 fields, `travelDistance` and `timeId` – Willem Oct 21 '21 at 08:42
  • @Willem irrelevant to the question though. – Scary Wombat Oct 21 '21 at 08:43
  • 2
    You can consider native query https://www.baeldung.com/spring-data-jpa-query – Popeye Oct 21 '21 at 08:44
  • 1
    annotate the field with the `@Column(name="TravelDistanceAndTimeId")` and have the java field named without the *and* `long TravelDistanceTimeId;` then name the method as `findByTravelDistanceTimeId` see https://stackoverflow.com/questions/41296713/spring-jpa-hibernate-findby-column-name-return-empty-collection – Scary Wombat Oct 21 '21 at 08:47
  • @Willem, you can think about this as a reference to a `TraveDistanceAndTime` entity, but my question is not specific to this one example. – tuesday Oct 22 '21 at 10:27

1 Answers1

1

Like Popeye said, consider using a native query as follows:

@Query(value = "SELECT <columns> FROM <TableName> WHERE travelDistanceAndTimeId=?1", nativeQuery = true)
public <returnType> findByTravelDistanceAndTimeId(long travelDistanceAndTimeId);
Dharman
  • 30,962
  • 25
  • 85
  • 135
  • 1
    Hi, is there any restriction to use native? a jpql query would also work I suppose e.g. `"SELECT e FROM Employee e WHERE e.travelDistanceAndTimeId=?1"` – pleft Oct 21 '21 at 09:21