问题
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 ?
回答1:
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
回答2:
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();
来源:https://stackoverflow.com/questions/13017411/how-to-create-custom-insert-into-query-in-ebean