Erroneous Boolean Mapping Hibernate (ArrayIndexOutOfBoundsException)

后端 未结 2 759
没有蜡笔的小新
没有蜡笔的小新 2020-12-22 04:04

I have a persistend Book Class with the following properties

  • PropertyName -> HibernateMappingType -> JavaType
  • id -> long -> long
相关标签:
2条回答
  • 2020-12-22 04:43

    There are two ways you can achieve the type conversion of attribute

    By annotating field with Type

    @Type(type = "yes_no")
    private boolean isActive;
    

    in DB Y/N will get persisted.

    By writing a converter

    @Column
    @Convert(converter = BooleanConverter.class)
    private boolean isActive;
    

    Converter class

    public class BooleanConverter implements AttributeConverter<Boolean, Character> {
    
        @Override
        public Character convertToDatabaseColumn(Boolean attribute) {
            if (attribute)
                return 'Y';
            else
                return 'N';
        }
    
        @Override
        public Boolean convertToEntityAttribute(Character dbData) {
            if ('Y' == dbData)
                return true;
            else
                return false;
        }
    
    }
    

    in xml you can replace the type attribute with the converter class name or yes_no

    <property name="status" column="book_status" type="yes_no" not-null="true"/>
    
    0 讨论(0)
  • 2020-12-22 04:47

    From what I see you are trying to map the BIT type in Database to Boolean in your hibernate code.

    There is a bug in MySQL with BIT Value, from version 5.0.3 onwards, in that it does not store a single BIT value. It stores something like SET or ENUM. And that often throws up issues, when you are doing a numeric value comparison. For more details check here

    http://www.xaprb.com/blog/2006/04/11/bit-values-in-mysql/

    You could ask your DBA to change the datatype to tinyint, however if that is not possible, you can change the status mapping from boolean to numeric_boolean, so would be something like

    <property name="status" column="book_status" type="numeric_boolean" not-null="true"/>
    
    0 讨论(0)
提交回复
热议问题