Example usage for javax.persistence CascadeType MERGE

List of usage examples for javax.persistence CascadeType MERGE

Introduction

In this page you can find the example usage for javax.persistence CascadeType MERGE.

Prototype

CascadeType MERGE

To view the source code for javax.persistence CascadeType MERGE.

Click Source Link

Document

Cascade merge operation

Usage

From source file:org.apache.openjpa.persistence.AnnotationPersistenceMetaDataParser.java

/**
 * Set cascades on relation.//from  www .  ja  va2 s .  c o m
 */
private void setCascades(ValueMetaData vmd, CascadeType[] cascades) {
    for (CascadeType cascade : cascades) {
        if (cascade == CascadeType.ALL || cascade == CascadeType.REMOVE)
            vmd.setCascadeDelete(ValueMetaData.CASCADE_IMMEDIATE);
        if (cascade == CascadeType.ALL || cascade == CascadeType.PERSIST)
            vmd.setCascadePersist(ValueMetaData.CASCADE_IMMEDIATE);
        if (cascade == CascadeType.ALL || cascade == CascadeType.MERGE)
            vmd.setCascadeAttach(ValueMetaData.CASCADE_IMMEDIATE);
        if (cascade == CascadeType.ALL || cascade == CascadeType.DETACH)
            vmd.setCascadeDetach(ValueMetaData.CASCADE_IMMEDIATE);
        if (cascade == CascadeType.ALL || cascade == CascadeType.REFRESH)
            vmd.setCascadeRefresh(ValueMetaData.CASCADE_IMMEDIATE);
    }
}

From source file:org.apache.openjpa.persistence.AnnotationPersistenceMetaDataSerializer.java

/**
 * Serialize cascades./*from   ww w .  j a v a  2  s  .c  om*/
 */
private void serializeCascades(ValueMetaData vmd, AnnotationBuilder ab) {
    EnumSet<CascadeType> cascades = EnumSet.noneOf(CascadeType.class);
    if (vmd.getCascadePersist() == ValueMetaData.CASCADE_IMMEDIATE) {
        cascades.add(CascadeType.PERSIST);
    }
    if (vmd.getCascadeAttach() == ValueMetaData.CASCADE_IMMEDIATE) {
        cascades.add(CascadeType.MERGE);
    }
    if (vmd.getCascadeDelete() == ValueMetaData.CASCADE_IMMEDIATE) {
        cascades.add(CascadeType.REMOVE);
    }
    if (vmd.getCascadeRefresh() == ValueMetaData.CASCADE_IMMEDIATE) {
        cascades.add(CascadeType.REFRESH);
    }
    if (vmd.getCascadeDetach() == ValueMetaData.CASCADE_IMMEDIATE) {
        cascades.add(CascadeType.DETACH);
    }
    if (cascades.size() == 5) // ALL
    {
        cascades.clear();
        cascades.add(CascadeType.ALL);
    }
    if (!cascades.isEmpty()) {
        ab.add("cascade", cascades);
    }
}

From source file:org.batoo.jpa.core.impl.model.mapping.AssociationMapping.java

/**
 * @param parent/*from  ww w . ja  va  2 s.  c  o  m*/
 *            the parent mapping
 * @param metadata
 *            the metadata
 * @param attribute
 *            the attribute
 * 
 * @since $version
 * @author hceylan
 */
public AssociationMapping(ParentMapping<?, Z> parent, AssociationAttributeMetadata metadata,
        AttributeImpl<? super Z, X> attribute) {
    super(parent, attribute, attribute.getJavaType(), attribute.getName());

    if ((metadata instanceof MappableAssociationAttributeMetadata)
            && StringUtils.isNotBlank(((MappableAssociationAttributeMetadata) metadata).getMappedBy())) {
        this.mappedBy = ((MappableAssociationAttributeMetadata) metadata).getMappedBy();
    } else {
        this.mappedBy = null;
    }

    this.eager = attribute.isCollection() || (this.mappedBy == null)
            ? metadata.getFetchType() == FetchType.EAGER
            : true;

    if (metadata instanceof OrphanableAssociationAttributeMetadata) {
        this.removesOrphans = ((OrphanableAssociationAttributeMetadata) metadata).removesOrphans();
    } else {
        this.removesOrphans = false;
    }

    this.cascadesDetach = metadata.getCascades().contains(CascadeType.ALL)
            || metadata.getCascades().contains(CascadeType.DETACH);
    this.cascadesMerge = metadata.getCascades().contains(CascadeType.ALL)
            || metadata.getCascades().contains(CascadeType.MERGE);
    this.cascadesPersist = metadata.getCascades().contains(CascadeType.ALL)
            || metadata.getCascades().contains(CascadeType.PERSIST);
    this.cascadesRefresh = metadata.getCascades().contains(CascadeType.ALL)
            || metadata.getCascades().contains(CascadeType.REFRESH);
    this.cascadesRemove = metadata.getCascades().contains(CascadeType.ALL)
            || metadata.getCascades().contains(CascadeType.REMOVE);
}

From source file:org.batoo.jpa.core.impl.model.mapping.AssociationMappingImpl.java

/**
 * @param parent/* w w w.  java2s .  com*/
 *            the parent mapping
 * @param metadata
 *            the metadata
 * @param attribute
 *            the attribute
 * 
 * @since 2.0.0
 */
public AssociationMappingImpl(AbstractParentMapping<?, Z> parent, AssociationAttributeMetadata metadata,
        AttributeImpl<? super Z, X> attribute) {
    super(parent, attribute, attribute.getJavaType(), attribute.getName());

    if ((metadata instanceof MappableAssociationAttributeMetadata)
            && StringUtils.isNotBlank(((MappableAssociationAttributeMetadata) metadata).getMappedBy())) {
        this.mappedBy = ((MappableAssociationAttributeMetadata) metadata).getMappedBy();
    } else {
        this.mappedBy = null;
    }

    this.eager = attribute.isCollection() || (this.mappedBy == null)
            ? metadata.getFetchType() == FetchType.EAGER
            : true;

    this.maxFetchDepth = metadata.getMaxFetchDepth();
    this.fetchStrategy = metadata.getFetchStrategy();

    if (metadata instanceof OrphanableAssociationAttributeMetadata) {
        this.removesOrphans = ((OrphanableAssociationAttributeMetadata) metadata).removesOrphans();
    } else {
        this.removesOrphans = false;
    }

    this.cascadesDetach = metadata.getCascades().contains(CascadeType.ALL)
            || metadata.getCascades().contains(CascadeType.DETACH);
    this.cascadesMerge = metadata.getCascades().contains(CascadeType.ALL)
            || metadata.getCascades().contains(CascadeType.MERGE);
    this.cascadesPersist = metadata.getCascades().contains(CascadeType.ALL)
            || metadata.getCascades().contains(CascadeType.PERSIST);
    this.cascadesRefresh = metadata.getCascades().contains(CascadeType.ALL)
            || metadata.getCascades().contains(CascadeType.REFRESH);
    this.cascadesRemove = metadata.getCascades().contains(CascadeType.ALL)
            || metadata.getCascades().contains(CascadeType.REMOVE);
}

From source file:org.bonitasoft.engine.bdm.RelationFieldAnnotator.java

public void annotateRelationField(final JDefinedClass entityClass, final RelationField field,
        final JFieldVar fieldVar) {
    JAnnotationUse relation = null;// w w w. j  av a2 s.com
    if (field.isCollection()) {
        relation = annotateMultipleReference(entityClass, field, fieldVar);
    } else {
        relation = annotateSingleReference(field, fieldVar);
    }

    if (field.isLazy()) {
        relation.param("fetch", FetchType.LAZY);
        codeGenerator.addAnnotation(fieldVar, JsonIgnore.class);
    } else {
        relation.param("fetch", FetchType.EAGER);
    }

    if (field.getType() == Type.COMPOSITION) {
        relation.param("cascade", CascadeType.ALL);
    } else if (field.getType() == Type.AGGREGATION) {
        relation.param("cascade", CascadeType.MERGE);
    }
}

From source file:org.bonitasoft.engine.business.data.generator.RelationFieldAnnotator.java

public void annotateRelationField(final JDefinedClass entityClass, final RelationField field,
        final JFieldVar fieldVar) {
    JAnnotationUse relation = null;//from w  w  w  .ja  v a2  s.  co m
    if (field.isCollection()) {
        relation = annotateMultipleReference(entityClass, field, fieldVar);
    } else {
        relation = annotateSingleReference(entityClass, field, fieldVar);
    }

    if (field.isLazy()) {
        relation.param("fetch", FetchType.LAZY);
        codeGenerator.addAnnotation(fieldVar, JsonIgnore.class);
    } else {
        relation.param("fetch", FetchType.EAGER);
    }

    if (field.getType() == Type.COMPOSITION) {
        relation.param("cascade", CascadeType.ALL);
    } else if (field.getType() == Type.AGGREGATION) {
        relation.param("cascade", CascadeType.MERGE);
    }

}

From source file:org.bonitasoft.engine.business.data.impl.BusinessDataServiceImpl.java

private Type getRelationType(final Entity businessObject, final String methodName)
        throws SBusinessDataRepositoryException {
    final String fieldName = ClassReflector.getFieldName(methodName);
    Annotation[] annotations;// w  w  w.  ja  va 2s .c o m
    try {
        annotations = businessObject.getClass().getDeclaredField(fieldName).getAnnotations();
    } catch (final NoSuchFieldException e) {
        return null;
    } catch (final SecurityException e) {
        throw new SBusinessDataRepositoryException(e);
    }
    for (final Annotation annotation : annotations) {
        final Set<Class<? extends Annotation>> annotationKeySet = getAnnotationKeySet();
        if (annotationKeySet.contains(annotation.annotationType())) {
            try {
                final Method cascade = annotation.getClass().getMethod("cascade");
                CascadeType[] cascadeTypes = (CascadeType[]) cascade.invoke(annotation);
                if (CascadeType.MERGE.equals(cascadeTypes[0])) {
                    return Type.AGGREGATION;
                }
                if (CascadeType.ALL.equals(cascadeTypes[0])) {
                    return Type.COMPOSITION;
                }
            } catch (Exception e) {
                throw new SBusinessDataRepositoryException(e);
            }
        }
    }
    return null;
}

From source file:org.finra.dm.dao.impl.DmDaoImpl.java

/**
 * Updates the audit fields if the entity is of type AuditableEntity.
 *
 * @param entity the entity//w w  w  .j  a v  a 2s .  c om
 * @param <T> the type of entity
 */
@SuppressWarnings("rawtypes")
private <T> void updateAuditFields(T entity) {
    if (entity instanceof AuditableEntity) {
        AuditableEntity auditableEntity = (AuditableEntity) entity;

        // Get the currently logged in username.
        String username = dmDaoSecurityHelper.getCurrentUsername();

        // Always set the updated by field, but only set the created by field when it is null (i.e. this is a new record).
        if (auditableEntity.getCreatedBy() == null) {
            auditableEntity.setCreatedBy(username);
        }
        auditableEntity.setUpdatedBy(username);

        // Always set the updated on field to the current time, but only update the created on field when it is null (i.e. the first time).
        Timestamp currentTime = new Timestamp(System.currentTimeMillis());
        auditableEntity.setUpdatedOn(currentTime);
        if (auditableEntity.getCreatedOn() == null) {
            auditableEntity.setCreatedOn(currentTime);
        }
    }

    // Try to update children one-to-many cascadable auditable entities.
    // Note that this assumes that OneToMany annotations are done on the field (as opposed to the method) and that all OneToMany fields are collections.
    // This approach also assumes that there are loops where children refer back to our entity (i.e. an infinite loop).
    // If there are other scenarios, we should modify this code to handle them.

    // Loop through all the fields of this entity.
    for (Field field : entity.getClass().getDeclaredFields()) {
        // Get all the annotations for the field.
        for (Annotation annotation : field.getDeclaredAnnotations()) {
            // Only look for OneToMany that cascade with "persist" or "merge".
            if (annotation instanceof OneToMany) {
                OneToMany oneToManyAnnotation = (OneToMany) annotation;
                List<CascadeType> cascadeTypes = new ArrayList<>(Arrays.asList(oneToManyAnnotation.cascade()));
                if ((cascadeTypes.contains(CascadeType.ALL)) || (cascadeTypes.contains(CascadeType.PERSIST))
                        || cascadeTypes.contains(CascadeType.MERGE)) {
                    try {
                        // Modify the accessibility to true so we can get the field (even if it's private) and get the value of the field for our entity.
                        field.setAccessible(true);
                        Object fieldValue = field.get(entity);

                        // If the field is a collection (which OneToMany annotated fields should be), then iterate through the collection and look for
                        // child auditable entities.
                        if (fieldValue instanceof Collection) {
                            Collection collection = (Collection) fieldValue;
                            for (Object object : collection) {
                                if (object instanceof AuditableEntity) {
                                    // We found a child auditable entity so recurse to update it's audit fields as well.
                                    updateAuditFields(object);
                                }
                            }
                        }
                    } catch (IllegalAccessException ex) {
                        // Because we're setting accessible to true above, we shouldn't get here.
                        throw new IllegalStateException("Unable to get field value for field \""
                                + field.getName() + "\" due to access restriction.", ex);
                    }
                }
            }
        }
    }
}

From source file:org.finra.herd.dao.impl.AbstractHerdDao.java

/**
 * Updates the audit fields if the entity is of type AuditableEntity.
 *
 * @param entity the entity/*from  w ww  . j a va2 s. c o m*/
 * @param <T> the type of entity
 */
@SuppressWarnings("rawtypes")
private <T> void updateAuditFields(T entity) {
    if (entity instanceof AuditableEntity) {
        AuditableEntity auditableEntity = (AuditableEntity) entity;

        // Get the currently logged in username.
        String username = herdDaoSecurityHelper.getCurrentUsername();

        // Always set the updated by field, but only set the created by field when it is null (i.e. this is a new record).
        if (auditableEntity.getCreatedBy() == null) {
            auditableEntity.setCreatedBy(username);
        }
        auditableEntity.setUpdatedBy(username);

        // Always set the updated on field to the current time, but only update the created on field when it is null (i.e. the first time).
        Timestamp currentTime = new Timestamp(System.currentTimeMillis());
        auditableEntity.setUpdatedOn(currentTime);
        if (auditableEntity.getCreatedOn() == null) {
            auditableEntity.setCreatedOn(currentTime);
        }
    }

    // Try to update children one-to-many cascadable auditable entities.
    // Note that this assumes that OneToMany annotations are done on the field (as opposed to the method) and that all OneToMany fields are collections.
    // This approach also assumes that there are loops where children refer back to our entity (i.e. an infinite loop).
    // If there are other scenarios, we should modify this code to handle them.

    // Loop through all the fields of this entity.
    for (Field field : entity.getClass().getDeclaredFields()) {
        // Get all the annotations for the field.
        for (Annotation annotation : field.getDeclaredAnnotations()) {
            // Only look for OneToMany that cascade with "persist" or "merge".
            if (annotation instanceof OneToMany) {
                OneToMany oneToManyAnnotation = (OneToMany) annotation;
                List<CascadeType> cascadeTypes = new ArrayList<>(Arrays.asList(oneToManyAnnotation.cascade()));
                if ((cascadeTypes.contains(CascadeType.ALL)) || (cascadeTypes.contains(CascadeType.PERSIST))
                        || cascadeTypes.contains(CascadeType.MERGE)) {
                    try {
                        // Modify the accessibility to true so we can get the field (even if it's private) and get the value of the field for our entity.
                        field.setAccessible(true);
                        Object fieldValue = field.get(entity);

                        // If the field is a collection (which OneToMany annotated fields should be), then iterate through the collection and look for
                        // child auditable entities.
                        if (fieldValue instanceof Collection) {
                            Collection collection = (Collection) fieldValue;
                            for (Object object : collection) {
                                if (object instanceof AuditableEntity) {
                                    // We found a child auditable entity so recurse to update it's audit fields as well.
                                    updateAuditFields(object);
                                }
                            }
                        }
                    } catch (IllegalAccessException ex) {
                        // Because we're setting accessible to true above, we shouldn't get here.
                        throw new IllegalStateException("Unable to get field value for field \""
                                + field.getName() + "\" due to access restriction.", ex);
                    }
                }
            }
        }
    }
}

From source file:org.orcid.persistence.jpa.entities.ProfileEntity.java

@OneToMany(mappedBy = "receiver", cascade = { CascadeType.DETACH, CascadeType.REFRESH, CascadeType.REMOVE,
        CascadeType.MERGE })
public Set<GivenPermissionByEntity> getGivenPermissionBy() {
    return givenPermissionBy;
}