Question
Is it possible for a JPA entity class to include multiple embedded fields, and how can I customize their column names without using @AttributeOverrides for each attribute?
@Entity
public class Person {
@Embedded
public Address home;
@Embedded
public Address work;
}
public class Address {
public String street;
public String city;
public String zipCode;
}
Answer
Yes, it is possible for a JPA entity to include multiple embedded fields, such as two instances of the same embedded class. However, customizing the column names when using multiple embedded fields can be challenging because JPA requires you to use @AttributeOverrides on each field manually, which can be cumbersome for large embedded classes.
@Entity
public class Person {
@Embedded
@AttributeOverrides({
@AttributeOverride(name = "street", column = @Column(name = "home_street")),
@AttributeOverride(name = "city", column = @Column(name = "home_city")),
@AttributeOverride(name = "zipCode", column = @Column(name = "home_zip_code"))
})
public Address home;
@Embedded
@AttributeOverrides({
@AttributeOverride(name = "street", column = @Column(name = "work_street")),
@AttributeOverride(name = "city", column = @Column(name = "work_city")),
@AttributeOverride(name = "zipCode", column = @Column(name = "work_zip_code"))
})
public Address work;
}
Causes
- JPA does allow multiple @Embedded annotations within a single entity class.
- The default behavior of Hibernate does not automatically distinguish differing embedded instances by column names if not specified.
Solutions
- Utilize @AttributeOverrides to manually specify column names for each embedded field, though this can become tedious with larger classes.
- Consider creating separate embedded classes if customization of many fields is necessary, which allows for clearer structure in the database schema.
Common Mistakes
Mistake: Failing to use @AttributeOverrides when expecting the column names to auto-generate based on the embedded fields.
Solution: Always specify @AttributeOverrides to customize column names for embedded fields.
Mistake: Not separating concerns if an embedded class becomes too large and complex.
Solution: If the embedded class has many fields, consider creating specific embedded classes tailored to the context they are used in.
Helpers
- JPA
- Hibernate
- Embedded fields
- @Embedded
- @AttributeOverrides
- JPA entity
- multiple embedded fields
- customizing column names