I've been assigned a task to unmarshal a XML file using JAXB and generate corresponding SQLs and fire to database. I've used following method to generate the list of SQLS.
public List<String> getSqlOfNationalityList(File file)throws JAXBException, FileNotFoundException, UnsupportedEncodingException {
List<String> unNationalityList = new ArrayList<String>();
JAXBContext jaxbcontext = JAXBContext.newInstance(ObjectFactory.class);
Unmarshaller unmarshaller = jaxbcontext.createUnmarshaller();
CONSOLIDATEDLIST consolidate = (CONSOLIDATEDLIST) unmarshaller.unmarshal(file);
// accessing individuals properties
INDIVIDUALS individuals = consolidate.getINDIVIDUALS();
List<INDIVIDUAL> list = individuals.getINDIVIDUAL();
for (INDIVIDUAL individual : list) {
NATIONALITY nationality = individual.getNATIONALITY();
if (nationality != null) {
List<String> values = nationality.getVALUE();
if (values != null) {
for (String value : values) {
String string2 = "";
StringBuffer builder = new StringBuffer();
builder.append("INSERT INTO LIST_UN_NATIONALITY");
builder.append("(" + "\"DATAID\"" + "," + "\"VALUE\"" + ")");
builder.append(" " + "VALUES(");
string2 = string2.concat("'" + individual.getDATAID() + "'" + ",");
if ("null ".contentEquals(value + " ")) {
string2 = string2.concat("' '" + ",");
} else {
string2 = string2.concat("'" + value.replace("'", "/") + "'" + ",");
}
if (string2.length() > 0) {
builder.append(string2.substring(0, string2.length() - 1));
}
builder.append(");");
builder.append("\r\n");
unNationalityList.add(builder.toString());
}
}
}
}
return unNationalityList;
}// end of file nationality List
I have used following method to read from the list and insert into database.
private void readListAndInsertToDb(List<String> list) {
int duplicateCount = 0;
int totalCount = 0;
try {
for (String sql : list) {
try {
int i = jdbcTemplate.update(sql);
} catch (DuplicateKeyException dke) {
// dke.printStackTrace();
duplicateCount++;
} catch (DataAccessException e) {
e.printStackTrace();
}
totalCount++;
} // end of for
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("\r\nTotal : " + totalCount);
System.out.println("Total duplicate : " + duplicateCount);
}
Now the issue is, I've about 13-14 similar type of lists. And the xml file consists of records which may already exist in database.
- How can I fire queries without making duplicate entries in the PostGres database.
- How it could be done in best optimal way? It would be great if executed in batch