In this tutorial we will learn about @MappedSuperclass and when we should use it.
And Simple Answer to that is you use it when you want to have have a super class that you don't want to create a table for it but just want to have it data attribute inheriated by its sub class like this
For example you got an abstract super class Book here that has an Id , title and isbn data attribute it; and we have annoted it @MappedSuperclass annotation and we got 2 sub class also like Ebook and Paperback. and Ebook sub class and Paperback sub class extending that Book super class, inheriting its id, title and isbn data attribute; and both the sub class is annotated with @Entity annotation we got the table for each sub class entity but no table for mapped super class which is annotated with @MappedSuperclass. What happens is when we persist an instance of sub class entity like when we persist Ebook object we will have table created for it with column all the data attribute inherited with books superclass we can see in diagram. Same with paperbook.
But the super class which Mapped with @MappedSupperclass annotation like Book super can't have table for itself.
So when you got a super class marked with the @MappedSuperclass annotation it can't also be marked as @Entity annotation. MappedSuperclass can't be an Entity as it doesn't have a sperate table defined for it. It just a MappedSuperclass not an Entity
So if want to have base class or super class to have your common data attributes for you so that you don't have specify in each of your sub class then we can simply annotated with @MappedSuperclass annotation and we can inheriate subclass from it. So basically super class with the mapped super class annotation lives only in your object model not in relation model which means from the data base perspective mapped super class is invisible but its data attribute are inheriated by its subclass and persisted to database table.
Reading data also quite efficient with mapped super class
Comments
Post a Comment