Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 18 Next »

Managed Object Design

Objects persisted via JPA are generally referred to as Managed Objects. In uPortal all domain objects are first defined by a public interface and then a concrete implementation with the JPA annotations is created. An example interface and implementation are included at the bottom of this section.

These guidelines should be used when creating Managed Objects in uPortal

  1. Define the domain object methods in an Interface
  2. The domain object should be data focused, it must not also encapsulate buisness logic.
  3. The implementation should be package private and exist in the same package as the DAO implementation and the DAO implementation should be the only class ever creating new instances of the managed object.
  4. A surrogate key must be defined as the primary @Id for the object, business keys must never be used as the primary @Id.
  5. An immutable natural key shouldbe defined. This is one or more fields that make up a unique business identity for the object.
    • These fields should be annotated with @NaturalId to gain significant performance improvements when querying using the natural id fields.
    • These fields should be marked as final and passed in via the constructor
  6. All nullable=false fields must be passed in via the constructor to prevent invalid object creation.
  7. A private no-arg constructor is required to allow Hibernate to create the object using reflection. This constructor is private to protect against invalid object creation.
  8. Both @TableGenerator and @SequenceGenerator annotations should be used to define the generator for the @GeneratedValue annotation. This allows for the maximum flexibility and consistency across databases.
  9. equals and hashCode must be implemented but must only ever include the fields that make up the unique business identity of the object.
    • For objects defined by an interface all efforts should be made to allow two different implementations of the same object to be equal to each other
  10. toString should be implemented and should as much information as is needed to easily identify the object but not too much that it clutters log files.
  11. Objects should define a version field annotated with @Version to support optimistic locking and data-integrity checks
Managed Object Examples
 IPortletType.java
public interface IPortletType {
    /**
     * Get the unique ID of this channel type.
     * 
     * @return unique id
     */
    public int getId();

    /**
     * Get the name of this channel type
     * 
     * @return channel type name
     */
    public String getName();

    /**
     * Get a description of this channel type
     * 
     * @return channel type description
     */
    public String getDescription();

    /**
     * Get the URI of the ChannelPublishingDocument associated with this
     * channel type.  This CPD will be used to determine configuration options 
     * for channels of this type.
     * 
     * @return ChannelPublishingDocument URI
     */
    public String getCpdUri();

    
    // Setter methods
    
    /**
     * Set the description for this channel type
     * 
     * @param description
     */
    public void setDescription(String descr);

    /**
     * Set the URI of the ChannelPublishingDocument associated with this channel
     * type.  This CPD will be used to determine configuration options for 
     * channels of this type.
     * 
     * @param ChannelPublishingDocument URI
     */
    public void setCpdUri(String cpdUri);
}
 PortletTypeImpl.java
@Entity
@Table(name = "UP_PORTLET_TYPE")
@SequenceGenerator(
        name="UP_PORTLET_TYPE_GEN",
        sequenceName="UP_PORTLET_TYPE_SEQ",
        allocationSize=1
    )
@TableGenerator(
        name="UP_PORTLET_TYPE_GEN",
        pkColumnValue="UP_PORTLET_TYPE",
        allocationSize=1
    )
@NaturalIdCache
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
class PortletTypeImpl implements Serializable, IPortletType {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(generator = "UP_PORTLET_TYPE_GEN")
    @Column(name = "TYPE_ID")
    private final int internalId;

    @Version
    @Column(name = "ENTITY_VERSION")
    private final long entityVersion;

    @NaturalId
    @Column(name = "TYPE_NAME", length = 70, nullable = false)
    private final String name;

    @Column(name = "TYPE_DESCR", length = 2000)
    private String descr;

    @Column(name = "TYPE_DEF_URI", length = 255, nullable = false)
    private String cpdUri;
    
    /**
     * Default constructor used by hibernate
     */
    @SuppressWarnings("unused")
    private PortletTypeImpl() {
        this.internalId = -1;
        this.name = null;
    }
    
    PortletTypeImpl(String name, String cpdUri) {
        this.internalId = -1;
        this.name = name;
        this.cpdUri = cpdUri;
    }

    @Override
    public int getId() {
        return this.internalId;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public String getDescription() {
        return descr;
    }

    @Override
    public String getCpdUri() {
        return cpdUri;
    }

    @Override
    public void setDescription(String descr) {
        this.descr = descr;
    }

    @Override
    public void setCpdUri(String cpdUri) {
        this.cpdUri = cpdUri;
    }

    @Override
    public boolean equals(Object object) {
        if (object == this) {
            return true;
        }
        if (!(object instanceof IPortletType)) {
            return false;
        }
        IPortletType rhs = (IPortletType) object;
        return new EqualsBuilder()
            .append(this.name, rhs.getName())
            .isEquals();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(-1497407419, 1799845985)
            .append(this.name)
            .toHashCode();
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
            .append("name", this.name)
            .append("cpdUri", this.cpdUri)
            .toString();
    }
}

JPA DAO Design

JPA DAOs are generally not that complex CRUD style data access objects. There a few design patterns that must be followed for all uPortal JPA DAOs.

  1. All JPA DAO must extend from BasePortalJpaDao. This class provides common functionality for building and executing queries that should be used by all JPA DAOs.
  2. The DAO must have a create method that takes in as parameters all the data required to create an persist the entity. This method will call the package-private constructor of the managed object and then must call entityManager.persist() before returning the managed object. Unattached JPA Managed Objects should never exist in uPortal.
  3. Wherever possible the DAO should use the CriteriaBuilder API and the JPA MetaModel. These tools all for 100% type safe and re-factoring safe queries.
JPA DAO Examples
 IPortletTypeDao.java
public interface IPortletTypeDao {
    /**
     * Creates, initializes and persists a new {@link IPortletType} based on the specified parameters
     * 
     * @param name The name of the channel type
     * @param cpdUri The URI to the CPD file used when publishing channels of this type
     * 
     * @return A newly created, initialized and persisted {@link IPortletType}
     * @throws org.springframework.dao.DataIntegrityViolationException If a IChannelType already exists for the provide arguments
     * @throws IllegalArgumentException If any of the parameters are null
     */
    public IPortletType createPortletType(String name, String cpdUri);
    
    /**
     * Persists changes to a {@link IPortletType}.
     * 
     * @param type The channel type to store the changes for
     * @throws IllegalArgumentException if type is null.
     */
    public IPortletType updatePortletType(IPortletType type);
    
    /**
     * Removes the specified {@link IPortletType} from the persistent store.
     * 
     * @param type The type to remove.
     * @throws IllegalArgumentException if type is null.
     */
    public void deletePortletType(IPortletType type);
    
    /**
     * Get a {@link IPortletType} for the specified id.
     * 
     * @param id The id to get the type for.
     * @return The channel type for the id, null if no type exists for the id.
     */
    public IPortletType getPortletType(int id);
    
    /**
     * Get a {@link IPortletType} for the specified name
     * 
     * @param name The name to get the type for.
     * @return The channel type for the name, null if no type exists for the fname.
     * @throws IllegalArgumentException if name is null.
     */
    public IPortletType getPortletType(String name);
    
    /**
     * @return A {@link List} of all persisted {@link IPortletType}s
     */
    public List<IPortletType> getPortletTypes();

}
 JpaPortletTypeDao.java
@Repository
public class JpaPortletTypeDao extends BaseJpaDao implements IPortletTypeDao {
 private CriteriaQuery<PortletTypeImpl> findAllTypesQuery;
 private CriteriaQuery<PortletTypeImpl> findTypeByNameQuery;
 private ParameterExpression<String> nameParameter;
 private EntityManager entityManager;
 @PersistenceContext(unitName = "uPortalPersistence")
 public final void setEntityManager(EntityManager entityManager) {
 this.entityManager = entityManager;
 }
 
 @Override
 protected EntityManager getEntityManager() {
 return this.entityManager;
 }
 @Override
 public void afterPropertiesSet() throws Exception {
 this.nameParameter = this.createParameterExpression(String.class, "name");
 
 this.findAllTypesQuery = this.createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<PortletTypeImpl>>() {
 @Override
 public CriteriaQuery<PortletTypeImpl> apply(CriteriaBuilder cb) {
 final CriteriaQuery<PortletTypeImpl> criteriaQuery = cb.createQuery(PortletTypeImpl.class);
 criteriaQuery.from(PortletTypeImpl.class);
 return criteriaQuery;
 }
 });
 
 
 this.findTypeByNameQuery = this.createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<PortletTypeImpl>>() {
 @Override
 public CriteriaQuery<PortletTypeImpl> apply(CriteriaBuilder cb) {
 final CriteriaQuery<PortletTypeImpl> criteriaQuery = cb.createQuery(PortletTypeImpl.class);
 final Root<PortletTypeImpl> typeRoot = criteriaQuery.from(PortletTypeImpl.class);
 criteriaQuery.select(typeRoot);
 criteriaQuery.where(
 cb.equal(typeRoot.get(PortletTypeImpl_.name), nameParameter)
 );
 
 return criteriaQuery;
 }
 });
 }
 
 @Override
 @Transactional
 public void deletePortletType(IPortletType type) {
 Validate.notNull(type, "definition can not be null");
 
 final IPortletType persistentChanneltype;
 if (this.entityManager.contains(type)) {
 persistentChanneltype = type;
 }
 else {
 persistentChanneltype = this.entityManager.merge(type);
 }
 this.entityManager.remove(persistentChanneltype);
 }
 @Override
 @Transactional
 public IPortletType createPortletType(String name, String cpdUri) {
 Validate.notEmpty(name, "name can not be null");
 Validate.notEmpty(cpdUri, "cpdUri can not be null");
 
 final PortletTypeImpl channelType = new PortletTypeImpl(name, cpdUri);
 
 this.entityManager.persist(channelType);
 
 return channelType;
 }
 @Override
 public IPortletType getPortletType(int id) {
 return this.entityManager.find(PortletTypeImpl.class, id);
 }
 @Override
 public IPortletType getPortletType(String name) {
 final TypedQuery<PortletTypeImpl> query = this.createCachedQuery(this.findTypeByNameQuery);
 query.setParameter(this.nameParameter, name);
 
 final List<PortletTypeImpl> channelTypes = query.getResultList();
 return DataAccessUtils.uniqueResult(channelTypes);
 }
 @Override
 public List<IPortletType> getPortletTypes() {
 final TypedQuery<PortletTypeImpl> query = this.createCachedQuery(this.findAllTypesQuery);
 final List<PortletTypeImpl> portletTypes = query.getResultList();
 return new ArrayList<IPortletType>(portletTypes);
 }
 @Override
 @Transactional
 public IPortletType updatePortletType(IPortletType type) {
 Validate.notNull(type, "type can not be null");
 
 this.entityManager.persist(type);
 
 return type;
 }
} 
  • No labels