Simplifying Default Enum Values in Embedded Classes with Hibernate

Home  >>  Technical Resources

In Java development, Hibernate is a very powerful tool for object-relational mapping (ORM), allowing seamless integration between Java objects and relational databases. One common scenario that software developers usually encounter in Hibernate is the need to assign default values to enums within embedded classes. Let's explore in this article about how to achieve this using Hibernate annotations.

Enum Defaults in Embedded Classes

Consider a situation where you have an enum Status with values ACTIVE and INACTIVE, and you want to embed it within another class EmbeddedEntity with a default value for status.

public enum Status {

    ACTIVE,

    INACTIVE

}


@Embeddable

public class EmbeddedEntity {

    @Enumerated(EnumType.STRING)

    private Status status;


    public EmbeddedEntity() {

        this.status = Status.ACTIVE; // Default value

    }


    // Getters and setters

    public Status getStatus() {

        return status;

    }


    public void setStatus(Status status) {

        this.status = status;

    }

}

In this example, @Embeddable marks EmbeddedEntity as embeddable in another entity, while @Enumerated(EnumType.STRING) specifies that enum values should be stored as strings. The constructor in EmbeddedEntity initializes status with the default value Status.ACTIVE.

Integrating with Hibernate Entities

To integrate this embedded class into a Hibernate entity, let's create an entity YourEntity:

@Entity

public class YourEntity {

    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    private Long id;


    private String name;


    private EmbeddedEntity embeddedEntity = new EmbeddedEntity();


    // Getters and setters

    public Long getId() {

        return id;

    }


    public void setId(Long id) {

        this.id = id;

    }


    public String getName() {

        return name;

    }


    public void setName(String name) {

        this.name = name;

    }


    public EmbeddedEntity getEmbeddedEntity() {

        return embeddedEntity;

    }


    public void setEmbeddedEntity(EmbeddedEntity embeddedEntity) {

        this.embeddedEntity = embeddedEntity;

    }

}

In YourEntity, the embeddedEntity field is automatically initialized with the default value due to its constructor in EmbeddedEntity.

In conclusion, Hibernate's support for default enum values in embedded classes simplifies software development tasks and ensures consistent data handling in Java applications.

Struggling with complex logic or maintaining large codebases? 

Our experienced Java developers are here to help.