Suggested Pages

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.

GenericBean.java

package com.simonefolinojavablog.persistence.entity;

...

@MappedSuperclass
public class GenericBean implements Serializable{

 @Id
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 private int id;

 public int getId() {
  return id;
 }

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

Contact.java

package com.simonefolinojavablog.persistence.entity;

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

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

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


 public int getNumber() {
  return number;
 }

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

 @Override
 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.
ContactDAO.java

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 -------");
  entityManager.persist(genericBean);
  System.out.println("------------save(): end -------");
 }
}

No comments :

Post a Comment

Suggested Pages