如何在hibernate JPA中实现PLSQL Materialized视图

时间:2015-05-22 13:03:14

标签: java hibernate postgresql jpa

我已经针对members表编写了一个实体化视图进行全文搜索:

CREATE MATERIALIZED VIEW member_search_index AS
SELECT member.memberid,
member.firstname,
member.lastname,
...
to_tsvector((COALESCE(member.lastname, ' '::character varying))::text) AS document
FROM member
GROUP BY member.memberid;

CREATE INDEX idx_member_search ON member_search_index USING gin(document);

我创建了实体并将其映射为:

@Entity
@Table(name = "MemberSearchIndex")
public class MemberSearch {
    @Id
    private long memberId;
    private String firstName;
    private String lastName;
...
}

这是我试图制作的SQL调用:

Query sqlQuery = entityManager.createNativeQuery("SELECT * FROM member_search_index WHERE document @@ to_tsquery('doe:*')", MemberSearch.class);

在这个例子中,我有一个硬编码值,我传递给查询doe,查询返回0个元素(它应该返回1)

所以:

  1. 我正确地进行了映射吗?
  2. 如何将参数传递给这样的本机查询?我试过这个.setParameter(1, searchQuery),但我在[1] couldn't be found
  3. 的例外情况

1 个答案:

答案 0 :(得分:0)

您可以使用JPQL查询而不是本机SQL。它看起来像这样:

Query query = entityManager.createQuery("
    SELECT ms 
    FROM MemberSearch ms 
    WHERE SQL('to_tsvector(''english'', ?) @@ to_tsquery(''english'', ?)', ms.document, ?1)
    ");

query.setParameter(1, "'doe:*'");
query.getResultList();