How to create custom INSERT INTO query in Ebean?

老子叫甜甜 提交于 2019-12-28 04:14:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!