Rookie B. Rookie B. - 1 year ago 200
Java Question

How to load / insert initial data into database with Ebean in Play Framework?

I need to some initial data (from csv files) into database. I am using Ebean with Play! Framework. I read the doc. It says using YAML files to store the data and call Ebean.save(). And this is done in a Test.

My questions:


  1. Where should I insert my data? (Test is probably not the ideal place, as this data should be used in production)

  2. Can I write my own code to get my data from existing csv files, instead of using YAML files?



Any suggestions or doc links will be appreciated.

Thanks!

Answer Source

With further search, I found the solution is described here

The code that perform initial insertion needs to be hooked into Play's startup.

Hooking into Play’s startup is as simple as creating a class called Global that implements GlobalSettings in the root package, and overriding the onStart() method. Let’s do that now, by creating the app/Global.java fileHooking into Play’s startup is as simple as creating a class called Global that implements GlobalSettings in the root package, and overriding the onStart() method. Let’s do that now, by creating the app/Global.java file

Note that, it said the class needs to be in the root package.

code example:

import play.*;
import play.libs.*;
import com.avaje.ebean.Ebean;
import models.*;
import java.util.*;

public class Global extends GlobalSettings {
    @Override
    public void onStart(Application app) {
        // Check if the database is empty
        if (User.find.findRowCount() == 0) {
            Ebean.save((List) Yaml.load("initial-data.yml")); // You can use whatever data source you have here. No need to be in YAML.
        }
    }
}