问题
I have a table named vehicle which has a column named VIN. Users need the ability to search based on the last 6 characters of the VIN. So I've added an index in Postgres like so:
CREATE INDEX "ix_vin_last_6" ON vehicle(RIGHT(vin,6));
I added a few test records as follows:
LAST6VIN_A_123456
LAST6VIN_B_123456
LAST6VIN_C_123456
Using SpringDataJPA repository, here is one way to query for the above test records:
List<Vehicle> findByVinEndingWith(String vin)
But the JPA query generated above uses a LIKE clause, like so:
where
vehicle0_.vin like ?
How do I make a repository method to query for the above 3 test records using the last 6 characters that uses the index I created above so that it generates this query:
SELECT vin, year, make, model
FROM vehicle
WHERE RIGHT(vin,6) = '123456';
The above query works fine when I execute it using pgadmin command line.
回答1:
JPQL supports (since JPA 2.1 IIRC) calling arbitrary database functions using function
:
select v from Vehicle v
where function('RIGHT', v.vin, 6) = :endOfVin
来源:https://stackoverflow.com/questions/31115100/jpa-query-using-a-database-function-to-use-a-specific-index