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
Hibernate provide option to execute native SQL queries through the use of SQLQuery object. Hibernate SQL Query is very handy when we have to execute database vendor specific queries that are not supported by Hibernate API.
You can use native SQL to express database queries if you want to utilize database-specific features such as query hints or the CONNECT keyword in Oracle. Hibernate 3. x allows you to specify handwritten SQL, including stored procedures, for all create, update, delete, and load operations.
You can implement these operations using JPQL, Criteria, or native queries. You can use the @Query annotation to define such a JPQL or native SQL statement. Because write operations need to be executed differently than read operations, you also need to annotate the repository method with a @Modifying annotation.
Wrap your query with begin end block. Like
EntityManager manager = getEntityManager(); Query q = manager.createNativeQuery("BEGIN " + sqlScript + " END;"); q.executeUpdate();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With