English 中文(简体)
JPA通过名称为本地人查询的IN条款清单
原标题:JPA passing list to IN clause in named native query

我知道,我能通过一份名单,在日本人民军中点名,但如何看待NamedNative Query? 我已经尝试了许多办法,但现在仍然只能把名单传给NamedNative Query。 任何人都知道如何通过NamedNative Query条款的清单? 非常感谢!

纳曼德Native 学历如下:

@NamedNativeQuery(
   name="User.findByUserIdList", 
   query="select u.user_id, u.dob, u.name, u.sex, u.address from user u "+
         "where u.user_id in (?userIdList)"
)

并且呼吁:

List<Object[]> userList = em.createNamedQuery("User.findByUserIdList").setParameter("userIdList", list).getResultList();

然而,结果与我预期的不一样。

System.out.println(userList.size());  //output 1

Object[] user = userList.get(0);
System.out.println(user.length);   //expected 5 but result is 3
System.out.println(user[0]);       //output MDAVERSION which is not a user_id
System.out.println(user[1]);       //output 5
System.out.println(user[2]);       //output 7
最佳回答

清单不能成为本土土地保有权的有效参数,因为清单不能在亚行约束。 你们需要在清单中给出每一论点的参数。

u.user_id in (?id1, ?id2)

这得到人民党的支持,但不是King,因此,你可以使用人民党,而不是原住民。

一些日本人民军协会的提供者可能支持这一点,因此,你可能希望与你的提供者结成联盟。

问题回答

www.un.org/Depts/DGACM/index_spanish.htm 以上已接受的答复是不正确的,使我走过了几天!

JPA 和Hibernate 均接受使用Query进行的本土垃圾收集。

你刚才需要做的事情

String nativeQuery = "Select * from A where name in :names"; //use (:names) for older versions of hibernate
Query q = em.createNativeQuery(nativeQuery);
q.setParameter("names", l);

这里的答案也是一样的(我从其中之一处举出上述例子)。

  1. Reference 1
  2. Reference 2 which mentioned which cases paranthesis works which giving the list as a parameter

* 表示这些参考资料涉及jpql查询,但收集资料的使用情况也与本地的询问有关。

简单明了:

@Query(nativeQuery =true,value = "SELECT * FROM Employee as e WHERE e.employeeName IN (:names)")  
 List<Employee> findByEmployeeName(@Param("names") List<String> names);

事实上,根据您的数据库/提供人/接收人/选择,你可以把一个附件的表列作为约束性参数,传递给人民军的一个原住民询问。

例如,与Pogres和EclipseLink一道,开展了以下工作(恢复真实性),展示了多层面阵容,以及如何实现一系列双重精确性。 (Do SlectT pg_type.* from pg_catalog.pg_type for other forms; may the those with _, but abolition out 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.

更谈这个问题——我不知道你如何或是否可以提出疑问;我认为,这个问题可能取决于。 但是,我想下面谈谈阿雷拉。

Array list = entityManager.unwrap(Connection.class).createArrayOf("int8", arrayOfUserIds);
List<Object[]> 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/

我可以采用记名、JPA 2.1和deltaspike数据,通过一份清单,作为电离层参数,载列IN条款。 我的询问如下。

@Query(value = "SELECT DISTINCT r.* FROM EVENT AS r JOIN EVENT AS t on r.COR_UUID = t.COR_UUID where " +
        "r.eventType= Creation  and t.eventType =  Reception  and r.EVENT_UUID in ?1", isNative = true)
public List<EventT> findDeliveredCreatedEvents(List<String> eventIds);

In jpa, it worked for me

@Query(nativeQuery =true,value = "SELECT * FROM Employee as e WHERE e.employeeName IN (:names)")  
List<Employee> findByEmployeeName(@Param("names") List<String> names);

在我的案件中(EclipseLink , PostGreSQL ),这项工作:

    ServerSession serverSession = this.entityManager.unwrap(ServerSession.class);
    Accessor accessor = serverSession.getAccessor();
    accessor.reestablishConnection(serverSession);
    BigDecimal result;
    try {
        Array jiraIssues = accessor.getConnection().createArrayOf("numeric", mandayWorkLogQueryModel.getJiraIssues().toArray());
        Query nativeQuery = this.entityManager.createNativeQuery(projectMandayWorkLogQueryProvider.provide(mandayWorkLogQueryModel));
        nativeQuery.setParameter(1,mandayWorkLogQueryModel.getPsymbol());
        nativeQuery.setParameter(2,jiraIssues);
        nativeQuery.setParameter(3,mandayWorkLogQueryModel.getFrom());
        nativeQuery.setParameter(4,mandayWorkLogQueryModel.getTo());
        result = (BigDecimal) nativeQuery.getSingleResult();
    } catch (Exception e) {
        throw new DataAccessException(e);
    }

    return result;

Also in query cannot use IN(?) because you will get error like :

产生于:org.postgresql.util.PSQLException: ERROR:营运人不存在:数字=数字。

IN(?) 必须转换成ANY(?)

我的解决办法是以埃尔汉尼斯概念为基础的。

Tried in JPA2 with Hibernate as provider and it seems hibernate does support taking in a list for "IN" and it works. (At least for named queries and I believe it will be similar with named NATIVE queries) What hibernate does internally is generate dynamic parameters, inside the IN same as the number of elements in the passed in list.

So in you example above

List<Object[]> userList = em.createNamedQuery("User.findByUserIdList").setParameter("userIdList", list).getResultList();

如果名单有2个要素,那么问询就象

select u.user_id, u.dob, u.name, u.sex, u.address from user u "+
         "where u.user_id in (?, ?)

如果它有3个要素,那么它就认为它愿意这样做。

select u.user_id, u.dob, u.name, u.sex, u.address from user u "+
         "where u.user_id in (?, ?, ?)

你们应当这样做:

String userIds ="1,2,3,4,5"; List<String> userIdList= Stream.of(userIds.split(",")).collect(Collectors.toList());

之后,在你问询中像参数一样通过:

@NamedNative Query (name=“User.findByUserIdList”, query=“select u.user_id, u.dob, u.name, u.sex, u.address fromuser u.user_id in (?userIdList)

不可能有标准的联合邮局。 Hibernate 提供所有权方法setPara amountList(>,但只与Hibernate Session合作,在JPA的 EntityManager中没有。

I came up with the following workaround for Hibernate, which is not ideal but almost standard JPA code and has some nice properties to it.

对于开户人来说,你可以在<条码>上保存被点名的原住地。 档案:

<named-native-query name="Item.FIND_BY_COLORS" result-class="com.example.Item">
    <query>
        SELECT i.*
        FROM item i
        WHERE i.color IN ( blue , :colors )
        AND i.shape = :shape
    </query>
</named-native-query>

The placeholder is wrapped in single quotes, so it s a valid native JPA query. It runs without setting a parameter list and would still return correct results when other matching color parameters are set around it.

Set the parameter list in your DAO or repository class:

@SuppressWarnings("unchecked")
public List<Item> findByColors(List<String> colors) {
    String sql = getQueryString(Item.FIND_BY_COLORS, Item.class);
    sql = setParameterList(sql, "colors", colors);

    return entityManager
            .createNativeQuery(sql, Item.class)
            .setParameter("shape",  BOX )
            .getResultList();
}

No manual construction of query strings. You can set any other parameter as you normally would.

Helper methods:

String setParameterList(String sql, String name, Collection<String> values) {
    return sql.replaceFirst(":" + name, String.join(" , ", values));
}

String getQueryString(String queryName, Class<?> resultClass) {
    return entityManager
            .createNamedQuery(queryName, resultClass)
            .unwrap(org.hibernate.query.Query.class) // Provider specific
            .getQueryString();
}

因此,我们基本上重新阅读了从orm.xml上显示的问询,人工设定了参数清单,然后建立了原住的JPA询问。 不幸的是,createNative Query (.getResultList (>>>回到了一种未分类的盘问和没有分类的清单,尽管我们通过了一个结果类别。 因此,@SuppressWarnings ("unchecked”)

Downside: Unwrapping a query without executing it may be more complicated or impossible for JPA providers other than Hibernate. For example, the following might work for EclipseLink (untested, taken from Can I get the SQL string from a JPA query object?):

Session session = em.unwrap(JpaEntityManager.class).getActiveSession();
DatabaseQuery databaseQuery =     query.unwrap(EJBQueryImpl.class).getDatabaseQuery();
databaseQuery.prepareCall(session, new DatabaseRecord());
Record r = databaseQuery.getTranslationRow();
String bound = databaseQuery.getTranslatedSQLString(session, r);
String sqlString = databaseQuery.getSQLString();

另一种办法是在文本档案中储存询问,并增加从那里读到的代码。

You can pass in a list as a parameter, but:

  • if you create a @NamedNativeQuery and use .createNamedQuery(), you don t use named param, you used ?1(positional parameter). It starts with 1, not 0.

  • 如果你使用<条码>.createNative Query(String),你可以使用点名。





相关问题
query must begin with SELECT or FROM: delete [delete

I am using JPA in addition to spring(3.0.0.M4). While deleting multiple records using query.executeUpdate() i am getting the following exception. org.springframework.web.util.NestedServletException: ...

Last update timestamp with JPA

I m playing around a bit with JPA(Eclipselink to be specific). The below entity have a timestamp that s supposed to reflect whenever that entity was last updated. What are the strategies for making ...

@IdClass with non primative @Id

I m trying to add a composite primary key to a class and having a bit of trouble. Here are the classes. class User { private long id; ... } class Token { private User user; private ...

Database not dropped in between unit test

Hello good people i came accross a weird behaviour in my test.I m using JPA hibernate annotation with spring. let say i have an Class MyObject and it s property email is marqued @Column(name="EMAIL", ...

Toplink trying to persist null object

I have an object "Instance" with another object "Course" inside. When trying to persist a new Instance object, I get the following error if Course is null: java.lang.IllegalStateException: During ...

How to prevent JPA from rolling back transaction?

Methods invoked: 1. Struts Action 2. Service class method (annotated by @Transactional) 3. Xfire webservice call Everything including struts (DelegatingActionProxy) and transactions is configured ...

热门标签