what is difference between MappedSuperclass and Embeddable and how should be we used

Viewed 2193

A MappedSuperclass uses inheritance for field and code reuse.

In addition we leverage some composition via Embeddable feature provided Hibernate

@Embeddable
public class Department {

private long deptId;
private String name;
private String description;
}

@Entity
@Table(name="CSE_DEPT", schema="test")
public class CSEDepartment{

@Embedded
private Department dept;
}

What is difference between @MappedSuperclass and @Embeddable and what is appropriate situation where they use.

1 Answers

@MappedSuperClass is good when we want to share some state between different entities so they will have the same fields and you can reuse the fields in your different entities. Generally it is created as a abstract class and you cannot create its own instance. You use this when you want to mimic the 'Is A' relationship. It cannot be used as a target for associations.

@Embeddable is used to map composite value types. @Embeddable class is used as one of the field type with in our entities. you can use this when you want to mimic 'Has A' relationship.

The case you have stated in the question, it may not be suitable for any. because both MappedSuperClass and Embeddable cannot be an entity..(you have departmentid in the department class which i am assuming should be a primary key). For your case better is to use @OneToOne entity association because cse department will have a uniqu id name and desc. you dont want to have 2 csedepartment in one college.

Related