Search code examples
javahibernate

Hibernate Attribute Converter Integer and String


I have int id of primary key in the hibernate entity and in the DTO object, I have same int id and String encId for encrypted primary key id. Every time when I transfer the entity to DTO using BeanUtils.copyProperties() to copy entity to DTO vise versa, in the next line I'm encrypt/decrypting and performing db operation.

Could you please help me how to use AttributeConverter<Integer, String> and to copy the bean I should only do BeanUtils.copyProperties() and no more enc/decrypt logic other than AttributeConverter. Please give me the sample snipet of Entity to DTO.


Solution

  • entity:

    @Entity
    public class Book {
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;
      
        @Convert(converter = IntegerToStringConverter.class)
        private Integer span;
    }
    

    converter

    @Converter
    public class IntegerToStringConverter
        implements AttributeConverter<Integer, String> {
    
         @Override
         public String convertToDatabaseColumn(Integer value) {
            
              try {
                  return Integer.toString(number);
              } else {
                  throw new IllegalStateException(
                         "Invalid number: " + value
                  );
              }
         }
     
         @Override
         public Integer convertToEntityAttribute(String number) {
    
             try {
                 return Integer.parseInt(number);   
             } catch(Exception e) {
                 throw new IllegalStateException(
                     "Invalid number: " + value
                 );
             }
         }
    
    }
    
    

    here is a running example