Wednesday, July 4, 2012

how to save a object in database using java



import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.Unmarshaller;
import org.exolab.castor.xml.ValidationException;
static final String saveReportSQLStat =
    "Insert into DOCUMENT_GEN " +
        "(ID_BUS, ID_BUS_FLNG, CD_DOC_TYPE, " +
            "TS_CREATED, DT_CYCLE, TX_DOCUMENT) " +
    "values(?, ?, 'FI', " +
            "?, ?, ?)";
public void saveReport(String businessID, String filingNumber,
        SavedReportResult savableReport, Connection con)
    throws CRDException, SQLException
{
    PreparedStatement prepStat = null;
    boolean newManager = false;
    if(savableReport == null)
        return;
   
    try{
        if(con == null){
            newManager = true;
            con = DBManager.getConnection();
        }
        prepStat = con.prepareStatement(saveReportSQLStat);
        prepStat.setString(1, businessID);
        prepStat.setString(2, filingNumber);
        prepStat.setTimestamp(3, DateFormatter.getInstance().getTimeStamp(savableReport.getFilingDate(), savableReport.getFilingTime()));
        prepStat.setString(4, savableReport.getFilingDate());
        if (savableReport != null) {
            StringWriter writer = new StringWriter();
       
            try {
                Marshaller.marshal(savableReport, writer);
            } catch (MarshalException e) {
                throw new CRDException(e.getMessage());
            } catch (ValidationException e) {
                throw new CRDException(e.getMessage());
            }
            ByteArrayInputStream is =
                new ByteArrayInputStream(writer.toString().getBytes());
            prepStat.setBinaryStream(5, is, is.available());
        } else {
            prepStat.setNull(5, Types.BLOB);
        }
        prepStat.execute();
        prepStat.close();
    }finally{
        if(prepStat != null)   
            prepStat.close();
        if(con != null && newManager)
            con.close();
        prepStat = null;
        con = null;       
    }
}

No comments:

Post a Comment