简体   繁体   中英

How can I add my own EnumValueMapperSupport

I'm trying to persist some enum s in Hibernate and it looks like my two options for built in support are to use the name of the enum, which I would rather not do because it's string based instead of int based, or the ordinal of the enum, which I would rather not do because if I add one of the enum values at the top of the class later on, I break everything down the line.

Instead, I have an interface called Identifiable that has public int getId() as part of its contract. This way, the enums I want to persist can implement Identifable and I can know that they'll define their own id.

But when I try to extend EnumValueMapperSupport so I can utilize this functionality, I'm greeted with errors from the compiler because the EnumValueMapper interface and the EnumValueMapperSupport class are not static, and thus are expected to be locked into a given EnumType object.

How can I extend this functionality in Hibernate, short of rewriting a bunch of Hibernate code and submitting a patch. If I can't, is there another way to somehow store an enum based on something other than the ordinal or name, but instead on your own code?

In a related thought, has anyone personally been down this road and decided "let's see how bad the name mapping is" and just went with name mapping because it wasn't that much worse performance? Like, is it possible I'm prematurely optimizing here?

I'm working against Hibernate version 5.0.2-final.

At least for Hibernate 4.3.5 the EnumValueMapper is static - although private.

But you can extend EnumValueMapperSupport in an extension of EnumType :

public class ExampleEnumType extends EnumType {

    public class ExampleMapper extends EnumValueMapperSupport {
      ...
    }

}

To create an instance of this mapper you need an instance of your EnumType :

ExampleEnumType type = new ExampleEnumType();
ExampleMapper mapper = type.new ExampleMapper();

Or you create it inside your type:

public class ExampleEnumType extends EnumType {

    public class ExampleMapper extends EnumValueMapperSupport {
        ...
    }

    public ExampleMapper createMapper() {
        return new ExampleMapper();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM