如何在 Ebean 中创建自定义 INSERT INTO 查询? [英] How to create custom INSERT INTO query in Ebean?

查看:24
本文介绍了如何在 Ebean 中创建自定义 INSERT INTO 查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要用大量数据填充一个表,所以我不想查找相关对象,而只想输入它们的数值.为此,我将构建一个简单的查询,即:

I need to fill a table with large amount of data so I don't want to find related objects, but just put numeric values of them. For this I'd build a simple query ie:

INSERT INTO article_category (article_id, category_id) VALUES (2,12);

无论如何都找不到用 Ebean 做到这一点的方法,我正在尝试:

anyway can't find a way to do this with Ebean, I was trying:

RawSql rawSql = RawSqlBuilder
    .parse("INSERT INTO article_category (article_id, category_id) VALUES (2,12)")
    .create();

然而,这会引发异常:

[RuntimeException: Error parsing sql, can not find SELECT 关键字 in:INSERT INTO article_category (article_id, category_id) VALUES (2,12)]

[RuntimeException: Error parsing sql, can not find SELECT keyword in:INSERT INTO article_category (article_id, category_id) VALUES (2,12)]

如何使用 Ebean 调用真正的原始查询?

How can I call really raw query with Ebean ?

推荐答案

其实我找到了一个解决方案,就是com.avaje.ebean.SqlUpdate 可用于 DELETES、UPDATES 和 INSERTS 语句:

Actually I found a solution, it's com.avaje.ebean.SqlUpdate which can be used for DELETES, UPDATES and INSERTS statements:

SqlUpdate down = Ebean.createSqlUpdate("DELETE FROM table_name WHERE id = 123");
down.execute(); 

SqlUpdate insert = Ebean.createSqlUpdate("INSERT INTO article_category (article_id, category_id) VALUES (2,12)");
insert.execute(); 

等等.当然,它还允许在查询中设置命名参数(来自其 API 的示例):

etc. Of course it also allows to set named parameters in the queries (sample from its API):

String s = "UPDATE f_topic set post_count = :count where id = :id"
SqlUpdate update = Ebean.createSqlUpdate(s);
update.setParameter("id", 1);
update.setParameter("count", 50);

int modifiedCount = Ebean.execute(update);

编辑

从数据库中选择没有对应模型的行也有类似的方法:com.avaje.ebean.SqlQuery

There is also similar method for selecting rows without corresponding models from DB: com.avaje.ebean.SqlQuery

这篇关于如何在 Ebean 中创建自定义 INSERT INTO 查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆