46

I have a SQL script with database dump. How can I execute it using Hibernate's EntityManager?

I tried it this way:

EntityManager manager = getEntityManager(); 
Query q = manager.createNativeQuery(sqlScript);
q.executeUpdate();

but it works only when sqlScript contains a single SQL query, while I need to run multiple inserts and other complex stuff.

RDBMS: Oracle Database 11g Express Edition Release 11.2.0.2.0 - 64bit Production

1
  • 1
    what is getEntityManager();???
    – TULSI JAIN
    Commented Nov 22, 2016 at 10:17

1 Answer 1

70

Wrap your query with begin end block. Like

EntityManager manager = getEntityManager(); 
Query q = manager.createNativeQuery("BEGIN " + sqlScript + " END;");
q.executeUpdate();
4
  • 1
    I'm getting You have an error in your SQL syntax with EclipseLink 2.6 and MySQL. Commented Jan 25, 2018 at 14:32
  • 2
    This answer for Oracle. Omit semicolon and it may work on MySql.
    – hkutluay
    Commented Mar 24, 2018 at 17:24
  • FYI: Doesn't work for me in Postgres.
    – Jurass
    Commented Mar 26 at 11:29
  • @Jurass can you try with do $$ before begin and $$ after end. enterprisedb.com/postgres-tutorials/…
    – hkutluay
    Commented Mar 26 at 13:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.