Sobes.tech
Junior — Middle

Can you explain the concept of Embeddable in JPA and how it is used to embed objects within entities?

sobes.tech AI

Answer from AI

In JPA, the @Embeddable annotation is used to designate a class whose objects can be embedded into an entity as part of its state, but which is not an entity with its own identifier.

This is convenient when you need to group several fields into a separate object for better code organization and reuse.

For example, if an entity User has an address consisting of street, city, and postal code, you can create an Address class with the @Embeddable annotation and embed it into User:

@Embeddable
public class Address {
    private String street;
    private String city;
    private String zipCode;

    // getters and setters
}

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

    private String name;

    @Embedded
    private Address address;

    // getters and setters
}

In this example, the fields street, city, and zipCode will be stored in the User table as columns, not in a separate table. This simplifies the database structure and allows logical grouping of related data.

Can you explain the concept of Embeddable in JPA and… - sobes.tech