在java中生成SQL字符串的好方法?
我不是在寻找像 Hibernate 这样的持久层,我只是想生成 SQL 字符串,它们应该与 PreparedStatement
。我尝试过 Squiggle 等库,但它只支持 SELECT
,我还想生成插入和更新。理想的用法是这样的:
generateInsertOn("myTable").addValue("value1").addValue("value2").generate();
这会生成这个字符串:
"INSERT INTO myTable (value1, value2) VALUES(?, ?)"
我知道存在与我的很相似的问题,例如 this,但他们并没有和我问同样的事情。
I'm not looking for a persistence layer like Hibernate, I just want to generate SQL-strings and they should be compatible with PreparedStatement
. I've tried libraries such as Squiggle, but it only supports SELECT
, I would also like to generate insert and updates. An ideal usage would be something like:
generateInsertOn("myTable").addValue("value1").addValue("value2").generate();
that would generate this string:
"INSERT INTO myTable (value1, value2) VALUES(?, ?)"
I know that there exists questions that are a lot like mine, such as this, but they don't quite ask the same thing as I do.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于任意 SQL,请使用 jOOQ。 jOOQ 目前支持
SELECT
、INSERT
、UPDATE
、DELETE
、TRUNCATE
和 <代码>合并。你可以这样创建SQL:支持的语法相当丰富。您还可以找到对
ON DUPLICATE KEY UPDATE
、FOR UPDATE
、LOCK IN SHARE MODE
等子句的支持。有关更多详细信息,请参阅
http://www.jooq.org
(免责声明,我在 jOOQ 背后的公司工作)
For arbitrary SQL, use jOOQ. jOOQ currently supports
SELECT
,INSERT
,UPDATE
,DELETE
,TRUNCATE
, andMERGE
. You can create SQL like this:The supported syntax is quite rich. You will also find support for clauses such as
ON DUPLICATE KEY UPDATE
,FOR UPDATE
,LOCK IN SHARE MODE
, etc.For more details, see
http://www.jooq.org
(Disclaimer, I work for the company behind jOOQ)
您绝对应该看看 SQLBuilder。它允许使用非常流畅的 API 进行简单而完整的 SQL 生成。
You should definitively take a look at SQLBuilder. It allows simple, yet complete, SQL generation using a very fluent API.
在这里冒险,你考虑过 iBatis 吗?它是一个真正实用的查询映射框架(我犹豫是否称其为 ORM 框架)。您必须创建像这样的 XML 文件:
它连接了像这样的映射器:
它允许您从这样的服务访问数据:
您可以将其与 Spring 连接:
另请参阅 完整的宠物店示例。
我不是 iBatis 的忠实粉丝,但它可能适合您在这种特定情况下的需求。
Going out on a limb here, have you considered iBatis? It's a real down to earth query mapping framework (I hesitate to call it an ORM framework somehow). You have to create XML files like this one:
which wires up a mapper like this one:
Which allows you to access data from services like this:
Which you can wire up with Spring:
See also the full petstore example.
I'm not an uniquivocal fan of iBatis but it might fit your needs in this specific case.