【问题标题】:Spring Boot JPA : How to map a filed to a column whose data type is not fixedSpring Boot JPA:如何将字段映射到数据类型不固定的列
【发布时间】:2020-02-14 06:15:37
【问题描述】:

我有一个包含两个字段的实体类。

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

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

  // getter and setter
  // manytoone with mandatory table

}

attributeValue 的数据类型在这里是 Object,这意味着 value 可以是 integer/boolean/float 之类的任何东西。

如何处理这种情况以保存正确的值并在获取时再次获得准确的值(布尔/整数等类型)??

【问题讨论】:

    标签: mysql hibernate jpa spring-data-jpa spring-boot-jpa


    【解决方案1】:

    您应该添加attribute 类标记字段Class<?> attributeClass。另一种方法是创建枚举AttributeType 并将其用作标记字段

    @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();
      }
    }
    

    要设置属性使用这个:

    Integer integerAttribute = 100;
    additionalAttributes.setAttribute(integerAttribute);
    
    Boolean booleanAttribute = true;
    additionalAttributes.setAttribute(booleanAttribute);
    

    然后有两种方法:

    1) 添加到实体或服务类 common attribute parcer

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

    用法:

    Object attribute = additionalAttributes.getAttribute();  
    

    2)或者使用pair方法获取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);
    }    
    
    //...
    

    用法:

    if(additionalAttributes.isIntegerAttribute()) {
        Integer integerAttribute = additionalAttributes.getIntegerAttribute(); 
        //...
    }
    
    if(additionalAttributes.isBooleanAttribute()) {
        Boolean booleanAttribute = additionalAttributes.getBooleanAttribute(); 
        //...
    }
    

    【讨论】:

    • 我应该在哪里使用 parseAttributevalue 方法?我没听懂你的方法,请解释一下
    猜你喜欢
    • 2016-05-06
    • 1970-01-01
    • 1970-01-01
    • 2012-10-08
    • 2016-01-13
    • 2019-05-10
    • 2012-01-21
    • 1970-01-01
    • 2021-12-08
    相关资源
    最近更新 更多