There are two types of objects in Hibernate
1. Value Object
2. Entities

Value Objects are the objects which can not stand alone. Take Address, for example. If you say address, people will ask whose address is this. So it can not stand alone.
Entity Objects are those who can stand alone like College and Student.

So in case of value objects preferred way is to Embed them into an entity object. In the example below Address class does not derive the meaning of its own. So Address is Value Object and is Embeddable. Whereas UserDetails(Entities) could stand on its own and it could have Embedded Objects

Address.java

 import javax.persistence.Embeddable;

@Embeddable
public class Address {
	private String Street;
	private String Location;
	private String City;
	
	public String getStreet() {
		return Street;
	}
	public void setStreet(String street) {
		Street = street;
	}
	public String getLocation() {
		return Location;
	}
	public void setLocation(String location) {
		Location = location;
	}
	public String getCity() {
		return City;
	}
	public void setCity(String city) {
		City = city;
	}
}

UserDetails.java

public class UserDetails 
{
 @Embedded
 private Address address;
 .
 .
 .
}

The above code explains how the Embedded and Embeddable annotations can be used in the code.

CreateUser.java

  Address objAddress = new Address();
  objUserDetail.setAddress(objAddress);

Attribute Override

@Embedded
@AttributeOverride (name="Street",column=@Column(name="HOME_STREET"))
private Address addr;

Multiple Attribute Overrides

@Embedded
 @AttributeOverrides({
	@AttributeOverride(name="doorNo", column=@Column(name="Office_DoorNo")),
	@AttributeOverride(name="streetName", column=@Column(name="Office_streetName")),
	@AttributeOverride(name="location", column=@Column(name="Office_location")),
	@AttributeOverride(name="pincode", column=@Column(name="Office_pincode"))
})
private Address addr;

Comments are closed.