Abdul
Abdul

Reputation: 1208

Why @Embeddable and @Embedded provided by Hibernate

Have Entity objects properly defined. Able to save data successfully.

@Embeddable
public class Address {

    private Integer houseNo;
    private String streetName;
    private String state, country;
}

@Entity
public class College {
    @Id
    @GeneratedValue
    private Integer collegeId;
    private String cName;

    @Embedded
    Address address;
}

But, When I use @Embeddable and @Embedded in hibernate application the final result looks like below.

mysql> select * from college;
+-----------+---------+---------+----------+--------------+-------+
| collegeId | country | houseNo | state    | streetName   | cName |
+-----------+---------+---------+----------+--------------+-------+
|         1 | Makkah  |     121 | Al-Azeed | Bilaal Stree | SMust |
+-----------+---------+---------+----------+--------------+-------+

My doubt is if Address fields have been saved in same table why we are using @Embeddable and @Embedded. Instead of that can't we define the Address fields directly in College entity?

Thank you.

Upvotes: 1

Views: 764

Answers (1)

Víctor Cabrera
Víctor Cabrera

Reputation: 56

Because of the use of best practices. Using composition for creating your entity favour the readability. And always you should favour composition over inheritance, and this's also valid for entities. Moreover, using classes for representing you model makes easier to map your java classes and your database tables. Additionally, Address class can be reused in another entities instead of repeating the same field once and again.

If you want to get Address class stored in another table then you can keep using composition but mapping your model with database relations. In the case you are asking for you would need to turn Address class into an @Entity and create a relation @OneToOne from College to Address.

@Entity
public class Address {

    @Id
    @GeneratedValue
    private Integer id;

    private Integer houseNo;

    private String streetName;

    private String state, country;
}

@Entity
public class College {

    @Id
    @GeneratedValue
    private Integer collegeId;

    private String cName;

    @OneToOne(optional = false)
    private Address address;
}

Upvotes: 1

Related Questions