How to create custom INSERT INTO query in Ebean?

biesior picture biesior · Oct 22, 2012 · Viewed 8.6k times · Source

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

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

however that throws an exception:

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

How can I call really raw query with Ebean ?

Answer

biesior picture biesior · Oct 23, 2012

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

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

Edit

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