0

I have an entity class with two fields.

@Entity(name = "additional_attributes")
class AdditionalAttributes {

  @Id
  private Integer id;
  private String attributeName;
  private Object attributevalue;

  // getter and setter
  // manytoone with mandatory table

}

The datatype of attributeValue is Object here, which means the value can be anything like integer/boolean/float.

How to handle this scenario to save the right value and again while fetching I should get the exact value (which was of type boolean/integer etc) ??

Randhir Ray
  • 540
  • 5
  • 14

1 Answers1

1

You should add attribute class marker field Class<?> attributeClass. Another approach is to create enum AttributeType and use it as marker field

@Entity(name = "additional_attributes")
class AdditionalAttributes {

  @Id
  private Integer id;
  private String attributeName;

  Class<?> attributeClass;
  String attributevalue;

  public void setAttribute(Object attribute){
      attributeClass = attribute.getClass()
      attributevalue = attribute.toString();
  }
}

To set attribute use this:

Integer integerAttribute = 100;
additionalAttributes.setAttribute(integerAttribute);

Boolean booleanAttribute = true;
additionalAttributes.setAttribute(booleanAttribute);

and then there are two approaches:

1) Add to entity or service class common attribute parcer

public Object getAttribute() throws NumberFormatException {
      if(attributeClass == Integer.class) {
          return Integer.parseInt(attributevalue);
      }

      if(attributeClass == Boolean.class) {
          return Boolean.parseBoolean(attributevalue);
      }

      //...
}

Usage:

Object attribute = additionalAttributes.getAttribute();  

2) Or use pair of methods to get attribute

public boolean isIntegerAttribute() {
   return attributeClass == Integer.class;
}

public Integer getIntegerAttribute() throws NumberFormatException {
   return Integer.parseInt(attributevalue);
}  

public boolean isBooleanAttribute() {
   return attributeClass == Boolean.class;
}

public Boolean getBooleanAttribute() {
   return Boolean.parseBoolean(attributevalue);
}    

//...

Usage:

if(additionalAttributes.isIntegerAttribute()) {
    Integer integerAttribute = additionalAttributes.getIntegerAttribute(); 
    //...
}

if(additionalAttributes.isBooleanAttribute()) {
    Boolean booleanAttribute = additionalAttributes.getBooleanAttribute(); 
    //...
}
Oleksii Valuiskyi
  • 2,691
  • 1
  • 8
  • 22