If we have a bean (i.e an object) inside a java bean rather than primitive type the how we map internal bean's property using OpenCSV
for example flightId of flight BEANS SCHEDULE(scheduleId,flight,route,and other fields)
Flight(flightid,other fields)
Route(routeId,otherfields)
package temp.csv;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.List;
import com.model.Schedule;
import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.bean.ColumnPositionMappingStrategy;
import au.com.bytecode.opencsv.bean.CsvToBean;
public class Abcd {
public static void main(String[] args) {
// TODO Auto-generated method stub
CsvToBean<Schedule> csv = new CsvToBean<Schedule>();
String csvFilename = "D:\\Travel_Portal\\Schedule\\SCHEDULE_4-10_12.26.54.csv ";
ColumnPositionMappingStrategy<Schedule> strat = new ColumnPositionMappingStrategy<Schedule>();
strat.setType(Schedule.class);
String[] columns = new String[] { "scheduleId", "flight.flightId",
"route.routeId", "availSourceDest", "availSourceVia",
"availViaDest", "fareSourceDest", "fareSourceVia",
"fareViaDest" };
// the fields to bind do in your JavaBean
strat.setColumnMapping(columns);
CSVReader csvReader = null;
try {
csvReader = new CSVReader(new FileReader(csvFilename));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
List<Schedule> list = csv.parse(strat, csvReader);
try {
for (Object object : list) {
Schedule schedule = (Schedule) object;
System.out.println(schedule.getScheduleId() + " "
+ schedule.getFlight() + schedule.getRoute());
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
//This is CSV file
"SID121","AI101","RID101",100,-1,-1,5000,-1,-1,"2013-10-20 11:30:00","0000-00-00 00:00:00","0000-00-00 00:00:00","2013-10-20 12:00:00","DID105"
//Schedule Class
public class Schedule implements java.io.Serializable {
private String scheduleId;
private Flight flight;
private Deal deal;
private Route route;
private int availSourceDest;
private Integer availSourceVia;
private Integer availViaDest;
private double fareSourceDest;
private double fareSourceVia;
private double fareViaDest;
private Date sourceTime;
private Date viaArrTime;
private Date viaDeptTime;
private Date destTime;
//getter and setter
}
//Flight
public class Flight implements java.io.Serializable {
private String flightId;
private Provider provider;
private int capacity;
//getter setter
}