Featured Post

Event Sourcing Video from Michael Ploed

Event Sourcing I want to share a great video I found few days ago that describes very well what Event Sourcing is.

Monday, June 18, 2012

JPA: GenericBean and Inheritance

In this post i'll show a way to outsource some entity properties. You can use inheritance to put in a superclass all the common properties shared among entities that extend it.
In the following snippet you can see GenericBean class that makes use of @MappedSuperclass annotation.
This annotation is used to tell JPA that the annotated class has a mapping to consider when you define entity that extends the superclass.


package com.simonefolinojavablog.persistence.entity;


public class GenericBean implements Serializable{

 private int id;

 public int getId() {
  return id;

 public void setId(int id) {
  this.id = id;


package com.simonefolinojavablog.persistence.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;

@Table(name = "Contacts")
public class Contact extends GenericBean {

 private static final long serialVersionUID = -2436155670557423751L;
 private int number;

 public int getNumber() {
  return number;

 public void setNumber(int number) {
  this.number = number;

 public String toString() {
  return "Contact [number=" + number + "]";


As you can see ContactDAO class uses GenericBean in its method signatures. In this way we can reduce the DAO class to write, because we only need a DAO class that persists, retrieves and edits GenericBean instead of particular entity bean.

package com.simonefolinojavablog.persistence.dao;


@Repository(value = "ContactDAORequired")
public class ContactDAO {

 @PersistenceContext(unitName = "persistenceUnitTest")
 private EntityManager entityManager;

 @Transactional(propagation = Propagation.REQUIRED)
 public void save(GenericBean genericBean) {
  System.out.println("------------save(): start -------");
  System.out.println("------------save(): end -------");

No comments :

Post a Comment