0

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 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent. This worked for me. I was able to use EXPLAIN to confirm that it is using the relevant index with this query. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.