Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting initial data JPA

Tags:

java

jpa

Is it possible to load initial data in my database ?

I am using JPA and am using the Drop and Create strategy, this way every time i want to test my application the database is first cleared and i would have to recreate everything all over again.

I know in other languages (Php -> Doctrine datafixtures, C# -> Context) it is possible to load initial data after the persistention of the classes.

However i tried searching for such feature in java and i can't find a good way to do this. I have found several topics across stackoverflow about this but none of them seem to have a good answer. I am using a java desktop application (not spring)

like image 243
Maxim Avatar asked Mar 08 '14 12:03

Maxim


1 Answers

This is totally possible. Your JPA implementation should have some mechanism to register a script for the drop and/or create phase. Here are some examples:

  • EclipseLink: see eclipselink.create-dll-jdbc-file-name http://wiki.eclipse.org/EclipseLink/Examples/JPA/DDL
  • Hibernate: even simpler, just put a file named import.sql on the classpath and select the right strategy (e.g. create-drop) (http://christopherlakey.com/articles/import-sql.html)
  • Persistence: source: http://docs.oracle.com/javaee/7/tutorial/persistence-intro005.htm

    <property name="javax.persistence.sql-load-script-source" value="META-INF/createDDL_ddlGeneration.sql" />
    

In case you only need this for testing, you could also prefill the database in a setup method. But obviously that would not be a JPA mechanism anymore.

like image 95
chris.tian Avatar answered Oct 12 '22 09:10

chris.tian