[英]How to get all the element from JDBC query
HI, HI,
I have query like this 我有这样的查询
final Query contractQuery = cgnDao.getEntityManager().
createNativeQuery("SELECT k.phrase, ak.type FROM key k INNER JOIN adkey ak USING (key_id) WHERE pck.pub_id =" + pid +" AND pck.c_id =" + campId );
How can i get each and every element from the query? 我如何从查询中获取每个元素?
Where phrase is an String and type is enum 其中短语是字符串,类型是枚举
in Java 在Java中
Thanks 谢谢
See both this link on the JBoss JPA docs and this link on java2s . 参见JBoss JPA文档上的 此链接和java2s上的此链接 。
In short, you have a Query on which you can call getResultList(), which returns a List you can iterate over. 简而言之,您有一个查询,可以在其上调用getResultList(),该查询返回一个可以迭代的List。 Have a look at the JPA javadoc .
看看JPA javadoc 。
Also, I'd recommend using PreparedStatements, something like 另外,我建议您使用PreparedStatements,例如
String sqlQuery = "select * from tbl_spaceship where owner = ?";
Query q = entityManager.createNativeQuery(sqlQuery, SpaceShip.class);
q.setParameter( 1, "Han" );
q.getResultList();
The advantage is that the JPA provider will take care of escaping the input values. 优点是JPA提供程序将转义输入值。 Not necessary at this particular use-case but good habits never hurt.
在此特定用例中没有必要,但良好的习惯永远不会受到伤害。
First of all, you shouldn't use String concatenation but positional parameters ( only positional parameter binding may be portably used for native queries ). 首先,您不应该使用String串联,而应该使用位置参数 ( 本机查询只能移植位置参数绑定 )。 Second, for a native query returning scalar values, the result would be a
List
of Oject[]
. 其次,对于返回标量值的本机查询,结果将是
List
of Oject[]
。 So the result might look like this: 因此结果可能如下所示:
String sql = "SELECT k.phrase, ak.type " +
"FROM key k INNER JOIN adkey ak USING (key_id) " +
"WHERE pck.pub_id = ?1 AND pck.c_id = ?2";
Query q = em.createNativeQuery(sql);
q.setParameter(1, pubId);
q.setParameter(2, cId);
List<Object[]> results = q.getResultList();
You can use value of method to gets enum instances from result set 您可以使用method的值从结果集中获取枚举实例
enum A {}
A.valueOf()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.