开发者

Mapping enum types with Hibernate Annotations

I have an enum开发者_如何转开发 type on my Java model which I'd like to map to a table on the database. I'm working with Hibernate Annotations and I don't know how to do that. Since the answers I search were rather old, I wonder which way is the best?

Thanks in advance


Do you need something else than the @Enumerated annotation? For example, the following enum:

public enum MyEnum { 
    VALUE1, VALUE2; 
}  

Could be used and annotated like this:

private MyEnum myEnum;
@Column(name="myenum") 
@Enumerated(EnumType.ORDINAL) 
public MyEnum getMyEnum() { 
    return myEnum 
}

You can specify how the enum should be persisted in the database with the EnumType enum property of the @Enumerated annotation. EnumType.ORDINAL specifies that the enum will be persisted as an integer value. Here, myEnum set to VALUE1 would be persisted as 0, VALUE2 as 1, etc.

The alternative is to use EnumType.STRING to specify that the enum will be persisted using the name of the enum value that the field is set to. So, applied to the previous example, setting the field myEnum to MyEnum.VALUE1 will persist as VALUE1, etc.


public enum OrderStatus {

    ORDER_CREATED,ORDER_COMPLETED,ORDER_CANCELLED
}

@Entity 
public class PurchaseOrder {
    
    @Enumerated(EnumType.STRING)
    private OrderStatus orderStatus;
    
}

Here OrderStatus is a referenced datatype(java object) , now you want to persist this OrderStatus in database, but its not possible to directly persist a java object into database now here @Enumerated(EnumType.STRING) comes into picture to convert that OrderStatus java object into String so that it can be persisted into DB.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜