How to use the Postgres any-clause with JPA/Hibernate native queries (array parameters)

廉价感情. 提交于 2019-12-01 14:43:38

I was able to work around this problem by unwrapping the Hibernate session from the EntityManager and use a JDBC PreparedStatement, which eats the java.sql.Array parameters without any complaint.

The NamedParameterStatement used in the example below is described here (I've modified it to my needs). It delegates to a PreparedStatement.

The rest of the code goes a little something like this:

public int executeUpdate(...){
    //....
    Integer customerID = 1;
    java.sql.Array userIDs  = toArray("integer", new int[]{111,222}));
    java.sql.Array deviceIDs= toArray("integer", new int[]{333,444}));

    final AtomicInteger rowsModifiedRef = new AtomicInteger();
    final Session session = em.unwrap(Session.class); // ATTENTION! This is Hibernate-specific!
    session.doWork((c) -> {
        try (final NamedParameterStatement statement = new NamedParameterStatement(c, queryString)) {
            statement.setObject("deviceIDs", userIDs);
            statement.setObject("userIDs", userIDs);
            statement.setObject("customerID", userIDs);
            rowsModifiedRef.set(statement.executeUpdate());
        }
    });
    return rowsModifiedRef.get();
}

private Array toArray(String typeName, Object... elements) {
    Session session = em.unwrap(Session.class); // ATTENTION! This is Hibernate-specific!
    final AtomicReference<Array> aRef = new AtomicReference<>();
    session.doWork((c) -> {
        aRef.set(c.createArrayOf(typeName, elements));
    });
    return aRef.get();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!