JPA custom script at startup

What is the best way to populate tables with jpa on application startup / shutdown? but with a data processing language instead of a data definition language. I am using HibernatePersistence as my continuity provider.

+2


source to share


4 answers


Solved by import.sql in the default package and select "create" as the value for hibernate.hbm2ddl.auto. Hibernate also supports the hibernate.hbm2ddl.import_files property .



+1


source


If you are also using spring then this answer will work.

If you are not using spring you have to run the DDL manually. Note that Hibernate has limited support for modifying the database (it can basically only create tables). Therefore, if you need anything else, you should use native SQL.

[EDIT] If you are not using spring you will find a way to get to Hibernate Session

. Call a method doWork()

that lets you run arbitrary SQL.



Another approach is to create domain objects and store them. However, I prefer the first approach, as you can fix the generated object ids this way and do other things that are more complex using the JPA interface.

You don't want to write a lot of statements insert

and then insert data into the DB and export it with a SQL tool like SquirrelSQL that can create statements for you insert

. Put them in an additional file, read the file at startup, split it into ;

and execute each part.

+2


source


I think populating your tables with low level sql insert statements is not the best option as you have to take care of the foreign keys manually and also refactor those statements with your code.

Since you already have an object model and ORM, another portable solution is to define your init data with your objects and let the JPA provider store it. While this solution may sound cumbersome, using projects like this makes it more believable.

0


source


For testing purposes, I used a simple groovy script and gmaven-plugin from org.codehaus.groovy.maven. The gmaven-plugin executes the groovy script and the script creates import.sql during the life cycle of the test-resources maven resource. Using loops and counters in a script is much better than manually printing a file filled with insert statements. This of course requires you to have the sorted hbm2ddl stuff, as it already looks like you already figured out from previous updates and answers.

0


source







All Articles