Search code examples
javadozer

Map java.sql.Time to Integer (milliseconds) with Dozer Mapper API


I have 2 classes

public class A
{
    public java.sql.Time startAt;
}

public class B
{
    public int startAt;
}

If I try to map it I get error that it cannot convert Time to Integer (milliseconds since 01.01.1970). Reading the docs I need to define customer converter. My question is

  1. How to do it with Dozer API
  2. Is there a way I could convert all instances of java.sql.Time to Integer? So I don't need to define converter for each class?

Solution

  • You make a custom class like this:

    import java.util.Date;
    
    import org.dozer.DozerConverter;
    import org.joda.time.DateTime;
    
    public class JodaTimeToDateConverter extends DozerConverter<Date, DateTime> {
    
    
      public JodaTimeToDateConverter() {
        super(Date.class, DateTime.class);
      }
    
    
      @Override
      public DateTime convertTo(Date source, DateTime destination) {
        DateTime result = null;
        if(source != null) {
          result = new DateTime(source.getTime());
        }
        return result;
      }
    
      @Override
      public Date convertFrom(DateTime source, Date destination) {
        Date result = null;
        if(source != null) {
          result = new Date(source.getMillis());
        }
        return result;
      }
    
    
    
    }
    

    Then, you add a configure block to the dozer xml:

    <configuration>
          <custom-converters>
                <converter type="foo.bar.CustomConverterClass">
                    <class-a>java.util.Date</class-a>
                    <class-b>org.joda.time.DateTime</class-b>
                </converter>
        </configuration>