JPA query using a database function to use a specific index

自闭症网瘾萝莉.ら 提交于 2019-12-13 06:33:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!