Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create custom INSERT INTO query in Ebean?

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 ?

like image 351
biesior Avatar asked Oct 22 '12 18:10

biesior


2 Answers

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

like image 158
biesior Avatar answered Sep 23 '22 14:09

biesior


You can also use plain old JDBC connection and statement instead of Ebean.

Something similar to this:

Connection connection = play.db.DB.getConnection();

Statement stmt = connection.createStatement();
stmt.executeUpdate("INSERT INTO article_category (article_id, category_id) VALUES (2,12)");

stmt.close();
like image 26
ndeverge Avatar answered Sep 23 '22 14:09

ndeverge