Menu

Embeddable Types and Enums

Embeddable Types and Enums

Embeddable Types

An embeddable class groups related fields, such as an address, and reuses them inside entities. It has no identity of its own, and its columns are stored in the owning entity's table.

The class is marked with @Embeddable, and the entity uses it through @Embedded. If you use the same embeddable twice in one entity, @AttributeOverride renames the columns to avoid a clash.

Enums

By default, Hibernate stores an enum by its position, which is EnumType.ORDINAL. Adding or reordering constants later silently corrupts existing data. Use EnumType.STRING so the name is stored instead.

@Embeddable
public class Address {
    private String city;
    private String pincode;
}

public enum Status { ACTIVE, INACTIVE }

@Entity
public class Student {
    @Id
    private Long id;

    @Embedded
    @AttributeOverride(name = "city", column = @Column(name = "home_city"))
    private Address address;

    @Enumerated(EnumType.STRING)
    private Status status;
}

Code Explanation:

  • Address has no @Id and no table. Its fields become columns of the Student table.
  • @AttributeOverride renames the city column to home_city.
  • @Enumerated(EnumType.STRING) stores ACTIVE or INACTIVE as text, so the data stays valid if the enum changes.

Hibernate Tutorial

AP

Abhishek Pati



Learn via Video Course

Java Programming ( Telugu) Logo

Java Programming ( Telugu)

11 hrs



Get in Touch For Details