使用数据库功能的JPA查询以使用特定索引 [英] JPA query using a database function to use a specific index
问题描述
我有一个名为vehicle的表,其中有一个名为VIN的列。
用户需要能够根据VIN的后6个字符进行搜索。
因此,我在Postgres中添加了一个索引,如下所示:
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
使用SpringDataJPA存储库,这是查询上述测试记录的一种方法:
Using SpringDataJPA repository, here is one way to query for the above test records:
List<Vehicle> findByVinEndingWith(String vin)
但是上面生成的JPA查询使用LIKE子句,如下所示:
But the JPA query generated above uses a LIKE clause, like so:
where
vehicle0_.vin like ?
我如何使用存储库方法使用最后6个字符来查询上述3条测试记录使用我在上面创建的索引,以便生成此查询:
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';
当我使用pgadmin命令行执行上述查询时,上述查询工作正常。
The above query works fine when I execute it using pgadmin command line.
推荐答案
JPQL支持(自JPA 2.1 IIRC起)使用 function $ c $调用任意数据库函数c>:
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
这篇关于使用数据库功能的JPA查询以使用特定索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!