Estou com um probleminha de utilizaação do tipo java.sql.Timestamp:
Crio um objeto para inclusão no banco de dados (estou utilizando no momento DB2 e SQLServer) utilizando java.util.Calendar / GregorianCalendar com a data atual (digamos, 2002-10-18 10:03:35.225).
Ao retornar do banco com Timestamp o valor é sempre diferente (digamos, 2002-10-18 10:03:35.226).
Ao comparar as duas datas - obviamente - elas são diferentes.
Esse problema dos milissegundos é ocasionado aparentemente pela divisão de Timestamp.getNanos() por 1000000, procedimento indicado na documentação (…guide/jdbc/getstart/mapping.html#1007474)
Edgar, você poderia colocar aqui o seu trecho de código? Acho que tenho idéia do que pode ser…
E
Edgar_Rocha_Mendonca
Aí está o código, Paulo.
Agradeço pela atenção.
// <DateUtils>/** * Retorna altera o Tipo Timestamp para Calendar * @return */publicstaticjava.util.CalendarconvertoToCalendar(java.sql.Timestampdata){GregorianCalendarcalendario=newGregorianCalendar();if(data.getNanos()>0){calendario.setTime(newjava.util.Date(data.getTime()+data.getNanos()/1000000));}else{calendario.setTime(newjava.util.Date(data.getTime()));}returncalendario;}/** * Retorna um Objeto Calendar correspondente a data da máquina * @return */publicstaticCalendargetCalendarCommonDate(){Calendarcurrent=newGregorianCalendar();DatecurrentTime=newDate();current.setTime(currentTime);returncurrent;}/** * Retorna um Objeto Calendar correspondente a data da máquina * @return */publicstaticjava.sql.TimestampconvertToSQLDate(Calendardata){returnnewjava.sql.Timestamp(data.getTime().getTime());}// </DateUtils>// <Acesso ao Banco>publicObjVOload(ObjPKpk)throwsDAOLoadException{if(!(pkinstanceofTesteMsgPK)){thrownewDAOLoadException("Não é um objeto do tipo esperado");}TesteMsgPKtesteMsgPK=(TesteMsgPK)pk;TesteMsgVOtesteMsgVO=newTesteMsgVO();PreparedStatementldStm=null;try{ldStm=VLstmContainer.getLoadStatement();ldStm.setLong(1,testeMsgPK.getId());ResultSetrs=ldStm.executeQuery();// A Busca pela chave primaria deve retornar apenas 1 linha.rs.next();testeMsgVO.setTesteMsgPK(newTesteMsgPK(rs.getLong("ID")));testeMsgVO.setDataEntrada(DateUtils.convertoToCalendar(rs.getTimestamp("dataEntrada")));testeMsgVO.setCodigoTeste(rs.getString("codigoTeste"));testeMsgVO.setDescricao(rs.getString("descricao"));testeMsgVO.setXML(rs.getString("xml"));testeMsgVO.setTipoXML(rs.getString("tipoXML"));}catch(SQLExceptione){thrownewDAOLoadException(e.getMessage());}catch(Exceptione){e.printStackTrace();}finally{try{ldStm.close();}catch(Exceptione){}}returntesteMsgVO;}publicObjPKsave(ObjVOvo)throwsDAOSaveException{if(!(voinstanceofTesteMsgVO)){thrownewDAOSaveException("Não é um objeto do tipo esperado");}TesteMsgVOtesteMsgVO=(TesteMsgVO)vo;PreparedStatementsvStm=null;try{svStm=VLstmContainer.getSaveStatement();svStm.setTimestamp(1,DateUtils.convertToSQLDate(testeMsgVO.getDataEntrada()));svStm.setString(2,testeMsgVO.getCodigoTeste());svStm.setString(3,testeMsgVO.getDescricao());svStm.setString(4,testeMsgVO.getXML());svStm.setString(5,testeMsgVO.getTipoXML());svStm.setLong(6,testeMsgVO.getTesteMsgPK().getId());svStm.executeUpdate();}catch(SQLExceptione){thrownewDAOSaveException(e.getMessage());}finally{try{svStm.close();}catch(Exceptione){}}returnnull;}// </Acesso ao Banco>// <Teste com JUnit>publicvoidtestSave(){TesteMsgDAOtesteMsgDAO=newTesteMsgDAO(TSTconnection);TesteMsgVOtesteMsgVO1=null;TesteMsgVOtesteMsgVO2=null;TesteMsgVOtesteMsgVO3=null;TesteMsgVOtesteMsgVO4=null;Calendaragora=DateUtils.getCalendarCommonDate();System.out.println("Save agora : "+DateUtils.calendarToDBDate(agora));try{testeMsgVO1=testeMsgDAO.load(newTesteMsgPK(1));testeMsgVO2=testeMsgDAO.load(newTesteMsgPK(1));}catch(DAOLoadExceptiondaol){System.out.println(daol.getMessage());}assertTrue(testeMsgVO2.equals(testeMsgVO1));testeMsgVO2.setCodigoTeste("ANOTHER");testeMsgVO2.setDataEntrada(agora);assertTrue(!(testeMsgVO2.equals(testeMsgVO1)));try{testeMsgDAO.save(testeMsgVO2);testeMsgVO3=testeMsgDAO.load(testeMsgVO2.getTesteMsgPK());testeMsgVO4=testeMsgDAO.load(testeMsgVO2.getTesteMsgPK());System.out.println("Save testeMsgVO3.getDataEntrada() : "+DateUtils.calendarToDBDate(testeMsgVO3.getDataEntrada()));System.out.println("Save testeMsgVO4.getDataEntrada() : "+DateUtils.calendarToDBDate(testeMsgVO4.getDataEntrada()));assertEquals(testeMsgVO3,testeMsgVO4);assertTrue(!testeMsgVO3.equals(testeMsgVO1));}catch(Exceptione){assertTrue(false);}}// </Teste com JUnit>
Paulo_Silveira
bem, se eu fosse voce, eu setaria o nanos do dia atual para 0, dessa maneira sempre ia ter 0 no nanos e nao ia dar problema
mas realmente, o problema eh o arredondamento de quando voce fazer o /100000. tente usar o Math.round na divisao, assim: