Add a relatively simple mechanism to read CSV and convert into object graphs for inserting or for callback to process how you like.
This example ... doesn't use a callback and will by default insert with JDBC batch size of 20.
try { File f = new File("src/test/resources/test1.csv"); FileReader reader = new FileReader(f); CsvReader<Customer> csvReader = Ebean.createCsvReader(Customer.class); csvReader.setPersistBatchSize(20); csvReader.addIgnore(); //csvReader.addProperty("id"); csvReader.addProperty("status"); csvReader.addProperty("name"); csvReader.addDateTime("anniversary", "dd-MMM-yyyy"); csvReader.addProperty("billingAddress.line1"); csvReader.addProperty("billingAddress.city"); csvReader.addReference("billingAddress.country.code"); csvReader.process(reader); } catch (Exception e) { throw new RuntimeException(e); }
The goal is just to make this very easy. This takes into account object hierarchy so for example, in the code above it actually creates a Customer and the Customer's billingAdress - binds the objects together... and inserts them.
For more complex behaviour you can use a callback.
This example uses a CsvCallback ... which means you get the objects back so that you can modify and process them as you want.
This also means you need to control the transaction and saving all yourself assuming you want to save the resulting object graphs.
try { File f = new File("src/test/resources/test1.csv"); FileReader reader = new FileReader(f); final EbeanServer server = Ebean.getServer(null); CsvReader<Customer> csvReader = server.createCsvReader(Customer.class); csvReader.setPersistBatchSize(2); csvReader.setLogInfoFrequency(3); csvReader.addIgnore(); //csvReader.addProperty("id"); csvReader.addProperty("status"); csvReader.addProperty("name"); csvReader.addDateTime("anniversary", "dd-MMM-yyyy"); csvReader.addProperty("billingAddress.line1"); csvReader.addProperty("billingAddress.city"); //processor.addReference("billingAddress.country.code"); csvReader.addProperty("billingAddress.country.code"); // when using CsvCallback we have to manage the transaction // and must save the bean(s) explicitly final Transaction transaction = Ebean.beginTransaction(); // use JDBC statement batching transaction.setBatchMode(true); transaction.setBatchSize(5); // you can turn off persist cascade if that is desired //transaction.setPersistCascade(false); // add a comment to the transaction log transaction.log("CsvReader loading test1.csv"); try { csvReader.process(reader, new CsvCallback<Customer>() { public void processBean(int row, Customer cust, String[] lineContent) { System.out.println(row + "> " + cust + " " + cust.getBillingAddress()); server.save(cust.getBillingAddress(), transaction); server.save(cust, transaction); } }); transaction.commit(); } finally { transaction.end(); } } catch (Exception e) { throw new RuntimeException(e); }
This code is now in HEAD.