将 SQL(不是 JPQL)映射到简单 Java 对象的集合?
我不敢相信我会问这个,但是...
在 Java 中,有没有办法执行 SQL 语句(不是 JPQL)并将结果映射到普通旧 Java 的 List
物体?
我希望能够创建小型轻量级 POJO 对象,然后用原始 SQL 查询填充它们。我明确不想要创建复杂的对象:只是基元,没有关系。
一切似乎都以 JPA/JPQL 为中心,但问题是我不想将我的对象绑定到特定的表。
我觉得我要么:
- (a) 服用疯狂的药物,要么
- (b) 错过了一些基本的东西
I can't believe I'm asking this, but...
Is there any way, in Java, to execute a SQL statement (not JPQL) and map the results to a List
of Plain Old Java Objects?
I want to be able to create small lightweight POJO objects and then have them populated by raw SQL queries. I'm expressly NOT looking to create complex objects: just primitives, with no relationships.
Everything seems to be centered around JPA/JPQL, but the problem with that is that I do not want to bind my objects to a specific table.
I feel like I'm either:
- (a) on crazy pills, or
- (b) missing something fundamental
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
轻量级映射器不能作为 JDK 本身的一部分提供。您可以使用 Java 的标准 JDBC API(事实上,JPA 实现建立在其之上),或者您可以查看提供简单 SQL 到对象映射器的外部库。我知道MyBatis(以前称为iBatis)。
A) 不,我认为您没有服用疯狂的药物,B) 您是否有可能只是错过了 JDBC?
A lightweight mapper is not available as part of the JDK itself. You could either roll-your-own simple mapper using Java's standard JDBC API (in fact JPA implementations build on top of that) or you could have a look at external libraries that provide simple SQL-to-Object mappers. I know MyBatis (formerly known as iBatis).
A) No, I think you're not on crazy pills and B) is it possible that you just missed JDBC?
Sormula 也许能够做你想做的事。您需要扩展 Table 并覆盖 getTableName() 和/或 getQualifiedTableName () 来提供所需的表名称,因为 sormula 通常将一个 POJO 关联到一张表。请参阅示例 2a 和 示例 3a。
Sormula may be able to do what you want. You would need to extend Table and override getTableName() and/or getQualifiedTableName() to supply the desired table name since sormula normally associates one POJO to one table. See example 2a and example 3a.
jOOQ 有几条记录 -> ; POJO 映射功能可能会为您完成这项工作(尽管 jOOQ 可以做更多事情)。这是一个示例:
摘自此处的手册:
http://www.jooq.org/doc/latest/ Manual/sql-execution/fetching/pojos/
Javadoc中描述了映射算法:
http://www.jooq.org/javadoc/latest/org /jooq/impl/DefaultRecordMapper.html
虽然上面的示例使用了 jOOQ 的 DSL API,但您也可以使用普通 SQL:
您甚至可以在 JDBC 上进行操作ResultSet,仅使用jOOQ进行映射:
jOOQ has a couple of Record -> POJO mapping capabilities that will probably do the job for you (although jOOQ can do much more). Here's an example:
Taken from the manual here:
http://www.jooq.org/doc/latest/manual/sql-execution/fetching/pojos/
The mapping algorithm is described in the Javadoc:
http://www.jooq.org/javadoc/latest/org/jooq/impl/DefaultRecordMapper.html
While the above example makes use of jOOQ's DSL API, you can do with plain SQL as well:
You can even operate on a JDBC ResultSet, using jOOQ only for mapping: