What is the purpose of the @Embeddable annotation in JPA?

Java MCQ: What is the purpose of the @Embeddable annotation in JPA?

a) To define an entity
b) To define a composite primary key
c) To define an embeddable class
d) To specify a named query

Answer:

c) To define an embeddable class

Explanation:

The @Embeddable annotation in JPA is used to define an embeddable class. An embeddable class is a type of class that does not have its own identity and is not an entity itself. Instead, it is embedded within another entity, and its fields are mapped to the same table as the owning entity.

Here’s an example:

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

    // Getters and setters
}

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

    @Embedded
    private Address address;

    private String name;

    // Getters and setters
}

In this example, the Address class is marked with the @Embeddable annotation, indicating that it can be embedded in other entities. The Employee entity contains an embedded Address, and the fields of Address are stored in the same table as Employee.

The @Embeddable annotation allows for cleaner and more modular design by enabling the reuse of value types in different entities.

Reference links:

https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top