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

查看:375
本文介绍了如何在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:解析sql时出错,无法在以下位置找到SELECT关键字:INSERT INTO article_category(article_id,category_id)值(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 ?

推荐答案

实际上我找到了一个解决方案,它是

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);

修改

还有一种类似的方法,用于从数据库中选择没有相应模型的行:

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

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

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