JPA passing list to IN clause in named native query

前端 未结 10 1076

I know I can pass a list to named query in JPA, but how about NamedNativeQuery? I have tried many ways but still can\'t just pass the list to a NamedNativeQuery. Anyone know

10条回答
  •  爱一瞬间的悲伤
    2020-11-30 08:07

    Depending on your database/provider/driver/etc., you can, in fact, pass a list in as a bound parameter to a JPA native query.

    For example, with Postgres and EclipseLink, the following works (returning true), demonstrating multidimensional arrays and how to get an array of double precision. (Do SELECT pg_type.* FROM pg_catalog.pg_type for other types; probably the ones with _, but strip it off before using it.)

    Array test = entityManager.unwrap(Connection.class).createArrayOf("float8", new Double[][] { { 1.0, 2.5 }, { 4.1, 5.0 } });
    Object result = entityManager.createNativeQuery("SELECT ARRAY[[CAST(1.0 as double precision), 2.5],[4.1, 5.0]] = ?").setParameter(1, test).getSingleResult();
    

    The cast is there so the literal array is of doubles rather than numeric.

    More to the point of the question - I don't know how or if you can do named queries; I think it depends, maybe. But I think following would work for the Array stuff.

    Array list = entityManager.unwrap(Connection.class).createArrayOf("int8", arrayOfUserIds);
    List userList = entityManager.createNativeQuery("select u.* from user u "+
         "where u.user_id = ANY(?)")
         .setParameter(1, list)
         .getResultList();
    

    I don't have the same schema as OP, so I haven't checked this exactly, but I think it should work - again, at least on Postgres & EclipseLink.

    Also, the key was found in: http://tonaconsulting.com/postgres-and-multi-dimensions-arrays-in-jdbc/

提交回复
热议问题