Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

...

Expand
PortletTypeImpl.java
PortletTypeImpl.java
Code Block
java
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)
public 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"//Hidden reference to the child portlet definitions, used to allow cascading deletes where when a portlet type is deleted all associated definitions are also deleted
    //MUST BE LAZY FETCH, this set should never actually be populated at runtime or performance will be TERRIBLE
    @OneToMany(mappedBy = "portletType", targetEntity = PortletDefinitionImpl.class, cascade = { CascadeType.ALL }, fetch = FetchType.LAZY, orphanRemoval = true)
    private transient Set<IPortletDefinition> portletDefinitions = null;

    @NaturalId
    @Column(name = "TYPE_NAME", length = 70)
    private PortletTypeImpl()final {String name;
       this.internalId = -1;
  @Column(name = "TYPE_DESCR", length = 2000)
    private this.name = nullString descr;
    }@Column(name = "TYPE_DEF_URI", length = 255, nullable = false)
   PortletTypeImpl(String name,private String cpdUri);
{    
    this.internalId = -1;/**
     * Default constructor used by this.namehibernate
= name;    */
    this.cpdUri = cpdUri;@SuppressWarnings("unused")
    private PortletTypeImpl() }{
     @Override   this.internalId = public-1;
int getId() {         return this.internalId;entityVersion = -1;
  }      @Overridethis.name = null;
  public String getName()}
{    
    returnpublic PortletTypeImpl(String name, String cpdUri) {
        this.internalId = -1;
        }this.entityVersion = -1;
   @Override     publicthis.name String getDescription() {= name;
        this.cpdUri return= descrcpdUri;
    }

    @Override
    public Stringint getCpdUrigetId() {
        return cpdUrithis.internalId;
    }
     @Override
    public voidString setDescriptiongetName(String descr) {
        this.descr = descrreturn name;
    }

    @Override
    public voidString setCpdUrigetDescription(String cpdUri) {
        this.cpdUri = cpdUrireturn descr;
    }

    @Override
    public booleanString equalsgetCpdUri(Object object) {
        ifreturn (objectcpdUri;
== this) {  }
    @Override
    public return true;
 void setDescription(String descr) {
      }  this.descr = descr;
    if}
(!(object instanceof IPortletType)) { @Override
    public void setCpdUri(String cpdUri) {
  return false;     this.cpdUri = cpdUri;
    }
    @Override
   IPortletType rhspublic =boolean equals(IPortletTypeObject obj) object;{
        if return(this new== EqualsBuilder(obj)
            .append(this.name, rhs.getName())return true;
        if (!(obj   .isEquals();instanceof IPortletType))
    }      @Override  return false;
 public int hashCode() {    IPortletType other    return new HashCodeBuilder(-1497407419, 1799845985)
= (IPortletType) obj;
          if .append(this.name == null) {
            if (other.toHashCodegetName(); != null)
  }      @Override     public String toString() {return false;
       return new}
ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)       else      .append("name", if (!this.name.equals(other.getName()))
             .append("cpdUri", this.cpdUri)return false;
        return true;
   .toString() }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
 } }

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
Expand
IPortletTypeDao.javaIPortletTypeDao.java
Code Block
javajava
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);
    
          result = prime * result + ((this.name == null) ? 0 : this.name.hashCode());
        return result;
    }
    @Override
    public String toString() {
        return "PortletTypeImpl [internalId=" + this.internalId + ", name=" + this.name + ", descr=" + this.descr
                + ", cpdUri=" + this.cpdUri + "]";
    }

    @Override
    public String getDataId() {
        return Integer.toString(getId());
    }

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

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

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. This ensures that later refactoring doesn't break queries.
JPA DAO Examples
Expand
IPortletTypeDao.java
IPortletTypeDao.java
Code Block
java
java
public interface IPortletTypeDao {
    /**
     * RemovesCreates, theinitializes specified {@link IPortletType} from the persistent store.
     * 
     * @param type The type to remove.
     * @throws IllegalArgumentException if type is null.
     */
    public void deletePortletType(IPortletType type);
   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 Getfile aused {@linkwhen IPortletType}publishing forchannels theof specifiedthis id.type
     * 
     * @param@return idA Thenewly idcreated, toinitialized getand thepersisted type for.{@link IPortletType}
     * @return The channel type@throws org.springframework.dao.DataIntegrityViolationException If a IChannelType already exists for the id, null if no type exists for the id.provide arguments
     * @throws IllegalArgumentException If any of the parameters are null
     */
    public IPortletType getPortletType(int idcreatePortletType(String name, String cpdUri);
    
    /**
     * GetPersists changes to 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 forto store the fname.changes for
     * @throws IllegalArgumentException if nametype is null.
     */
    public IPortletType getPortletTypeupdatePortletType(StringIPortletType nametype);
    
    /**
     * Removes the specified {@link IPortletType} from the persistent store.
     * 
     * @param type The type to remove.
  * @return A {@link* List}@throws ofIllegalArgumentException allif persistedtype {@link IPortletType}sis null.
     */
    public List<IPortletType>void getPortletTypesdeletePortletType(IPortletType type);
 } 
Expand
JpaPortletTypeDao.javaJpaPortletTypeDao.java
Code Block
javajava
/**
 * Licensed
to Jasig under one or more contributor license
 * agreements. See the NOTICE file distributed with this work
 * for additional information regarding copyright ownership. /**
     * Get a {@link IPortletType} for the specified id.
     * Jasig
licenses this file to you under* the@param Apacheid License,The id * Version 2.0 (the "License"); you may not use this fileto get the type for.
     * except@return The inchannel compliancetype withfor the License. You may obtain a
 * copy of the License at:
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.jasig.portal.portlet.dao.jpa;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import org.apache.commons.lang.Validate;
import org.jasig.portal.jpa.BasePortalJpaDao;
import org.jasig.portal.jpa.OpenEntityManager;
import org.jasig.portal.portlet.dao.IPortletTypeDao;
import org.jasig.portal.portlet.om.IPortletType;
import org.springframework.stereotype.Repository;
import com.google.common.base.Function;
/**
 * JPA/Hibernate implementation of IChannelTypeDao.  This DAO handles 
 * channel types and is not yet integrated with the channel definition persistence
 * code.
 * 
 * @author Jen Bourey, jbourey@unicon.net
 * @revision $Revision$
 */
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();

}
Expand
JpaPortletTypeDao.java
JpaPortletTypeDao.java
Code Block
java
java
@Repository
public class JpaPortletTypeDao extends BasePortalJpaDao implements IPortletTypeDao {
    private CriteriaQuery<PortletTypeImpl> findAllTypesQuery;
    @Override
    public void afterPropertiesSet() throws Exception {
        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;
            }
        });
    }
    
    
    @Override
    @PortalTransactional
    public void deletePortletType(IPortletType type) {
        Validate.notNull(type, "definition can not be null");
        
        final IPortletType persistentChanneltype;
        final EntityManager entityManager = this.getEntityManager();
        if (entityManager.contains(type)) {
            persistentChanneltype = type;
        }
        else {
            persistentChanneltype = entityManager.merge(type);
        }
        entityManager.remove(persistentChanneltype);
    }
    @Override
    @PortalTransactional
    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.getEntityManager().persist(channelType);
        
        return channelType;
    }
    @Override
    public IPortletType getPortletType(int id) {
        return this.getEntityManager().find(PortletTypeImpl.class, id);
    }
    @OpenEntityManager(unitName = PERSISTENCE_UNIT_NAME)
    @Override
    public IPortletType getPortletType(String name) {
        final NaturalIdQuery<PortletTypeImpl> query = this.createNaturalIdQuery(PortletTypeImpl.class);
        query.using(PortletTypeImpl_.name, name);
        return query.load();
    }
    @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
    @PortalTransactional
    public IPortletType updatePortletType(IPortletType type) {
        Validate.notNull(type, "type can not be null");
        
        this.getEntityManager().persist(type);
        
        return type;
    }
}