Why @Embeddable and @Embedded provided by Hibernate

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


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.





Of course you could, but wel live in an OO world so you want something that represents an Address. Just a collection of fields doesn't make it an address.
– M. Deinum
1 hour ago




1 Answer
1



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;
}






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Arduino Mega cannot recieve any sketches, stk500_recv() programmer is not responding

Visual Studio Code: How to configure includePath for better IntelliSense results

C++ virtual function: Base class function is called instead of derived