Question

What is the best way to fill tables create with jpa at application startup/shutdown of application ? like but with data manipulation language instead data definition language. i'm using HibernatePersistence as persistence provider.

Was it helpful?

Solution 2

Solved with import.sql in default package and selecting "create" as hibernate.hbm2ddl.auto value. Hibernate supports also hibernate.hbm2ddl.import_files property.

OTHER TIPS

If you're also using spring, then this answer will work.

If you're not using Spring, then you must run the DDL code manually. Note that Hibernate has only limited support to modify the database (it can basically only create tables). So if you need anything else, you must use custom SQL.

[EDIT] If you don't use Spring, then you find a way to get at the Hibernate Session. Invoke the doWork() method which allows to run arbitrary SQL.

A different approach is to create the domain objects and persist them. I prefer the first approach, though, since you can fixate the IDs of generated objects this way and do other things that are more complex using the JPA interface.

It you don't want to write lots of insert statements, then insert the data into the DB and export it with an SQL tool like SquirrelSQL which can create the insert statements for you. Put them into an extra file, read the file at startup, split it at ; and execute each piece.

I think filling your tables with low level sql insert statements is not the best option since you should manually take care of the foreign keys and also refactor these statements with your code.

Since you already have an object model and ORM, another more portable solution is to define your init data with your objects and let the JPA provider persist them. Although this solution might seem cumbersome, but using projects like this makes it more plausible.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top