Example usage for javax.persistence CascadeType PERSIST

List of usage examples for javax.persistence CascadeType PERSIST

Introduction

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

Prototype

CascadeType PERSIST

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

Click Source Link

Document

Cascade persist operation

Usage

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

/**
 * @param parent//from  www .j  a  v  a 2  s . co m
 *            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.finra.dm.dao.impl.DmDaoImpl.java

/**
 * Updates the audit fields if the entity is of type AuditableEntity.
 *
 * @param entity the entity//from  w w  w .j ava2 s  .co 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 = 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//w ww  .j  a  v a2s . co  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.kuali.rice.core.framework.persistence.jpa.metadata.MetadataManager.java

@SuppressWarnings("unchecked")
private static EntityDescriptor construct(Class clazz) {
    if (!clazz.isAnnotationPresent(Entity.class)) {
        return null;
    }// w  w  w .j a  va 2 s. com

    // Determine the base entity metadata
    EntityDescriptor entityDescriptor = new EntityDescriptor();
    entityDescriptor.setClazz(clazz);
    String defaultName = clazz.getName().substring(clazz.getName().lastIndexOf(".") + 1);
    Entity entity = (Entity) clazz.getAnnotation(Entity.class);
    if (StringUtils.isBlank(entity.name())) {
        entityDescriptor.setName(defaultName);
    } else {
        entityDescriptor.setName(entity.name());
    }
    if (clazz.isAnnotationPresent(Table.class)) {
        Table table = (Table) clazz.getAnnotation(Table.class);
        entityDescriptor.setTable(table.name());
    } else {
        entityDescriptor.setTable(defaultName);
    }
    if (clazz.isAnnotationPresent(IdClass.class)) {
        entityDescriptor.setIdClass(((IdClass) clazz.getAnnotation(IdClass.class)).value());
    }
    if (clazz.isAnnotationPresent(Sequence.class)) {
        entityDescriptor.setSequence((Sequence) clazz.getAnnotation(Sequence.class));
    }

    // Check for an "extension"
    try {
        Class extensionClass = Class.forName(clazz.getName() + "Extension");
        OneToOneDescriptor descriptor = new OneToOneDescriptor();
        descriptor.setCascade(new CascadeType[] { CascadeType.PERSIST });
        descriptor.setAttributeName("extension");
        descriptor.setTargetEntity(extensionClass);
        descriptor.setMappedBy("extension");
        EntityDescriptor extensionDescriptor = MetadataManager.getEntityDescriptor(extensionClass);
        for (FieldDescriptor fd : extensionDescriptor.getPrimaryKeys()) {
            descriptor.addFkField(fd.getName());
        }
        entityDescriptor.add(descriptor);
        FieldDescriptor extension = new FieldDescriptor();
        extension.setName("extension");
        extension.setClazz(extensionClass);
        entityDescriptor.add(extension);
    } catch (Exception e) {
    }

    List<Class> classes = new ArrayList<Class>();
    classes.add(clazz);
    Class c = clazz;
    while (!c.getSuperclass().equals(Object.class)) {
        c = c.getSuperclass();
        classes.add(c);
    }
    Collections.reverse(classes);

    // Determine the field/relationship metadata for all classes in the clazz hierarchy
    for (Class temp : classes) {
        extractFieldMetadata(temp, entityDescriptor);
        if (temp.isAnnotationPresent(AttributeOverrides.class)) {
            for (AttributeOverride override : ((AttributeOverrides) temp
                    .getAnnotation(AttributeOverrides.class)).value()) {
                entityDescriptor.getFieldByName(override.name()).setColumn(override.column().name());
            }
        }
        if (temp.isAnnotationPresent(AttributeOverride.class)) {
            AttributeOverride override = (AttributeOverride) temp.getAnnotation(AttributeOverride.class);
            entityDescriptor.getFieldByName(override.name()).setColumn(override.column().name());
        }
        //if (temp.isAnnotationPresent(AssociationOverrides.class)) {
        //   for (AssociationOverride override : ((AssociationOverrides)temp.getAnnotation(AssociationOverride.class)).value()) {
        //      entityDescriptor.getFieldByName(override.name()).;
        //   }
        //}
        //if (temp.isAnnotationPresent(AttributeOverride.class)) {
        //   AttributeOverride override = (AttributeOverride) temp.getAnnotation(AttributeOverride.class);
        //   entityDescriptor.getFieldByName(override.name()).setColumn(override.column().name());               
        //}

    }

    return entityDescriptor;
}

From source file:org.photovault.folder.PhotoFolder.java

@OneToMany(mappedBy = "parentFolder", cascade = { CascadeType.PERSIST, CascadeType.MERGE })
@org.hibernate.annotations.Cascade({ org.hibernate.annotations.CascadeType.SAVE_UPDATE })
@org.hibernate.annotations.Sort(type = org.hibernate.annotations.SortType.COMPARATOR, comparator = PhotoFolder.PhotoFolderComparator.class)
public SortedSet<PhotoFolder> getSubfolders() {
    return subfolders;
}

From source file:org.photovault.folder.PhotoFolder.java

/**
   Returns the parent of this folder or null if this is a top-level folder
*///from  w  ww.  j av  a2  s  .  c  om
@ValueField(dtoResolver = ParentRefResolver.class, setMethod = "reparentFolder")
@ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE })
@org.hibernate.annotations.Cascade({ org.hibernate.annotations.CascadeType.SAVE_UPDATE })
@JoinColumn(name = "parent_uuid", nullable = true)
// This is needed since OJB set parent to 0 for the root folder.
@org.hibernate.annotations.NotFound(action = org.hibernate.annotations.NotFoundAction.IGNORE)
public PhotoFolder getParentFolder() {
    return parent;
}

From source file:org.photovault.imginfo.ImageFile.java

/**
 * Get all images stored in this file//from   www.  ja v  a2s. c  o  m
 * @return Map that maps image location descriptor to the image descriptor object
 */
@MapKey(name = "locator")
@OneToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE }, mappedBy = "file")
@org.hibernate.annotations.Cascade({ org.hibernate.annotations.CascadeType.SAVE_UPDATE,
        org.hibernate.annotations.CascadeType.DELETE })
public Map<String, ImageDescriptorBase> getImages() {
    return images;
}

From source file:org.photovault.imginfo.PhotoInfo.java

/**
 Get image descriptor for original of this photo
 @return original's image descriptor./*from  w w  w .  j a v a 2s. com*/
 */
@ValueField(dtoResolver = OrigImageRefResolver.class)
@ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE })
@org.hibernate.annotations.Cascade({ org.hibernate.annotations.CascadeType.SAVE_UPDATE })
@JoinColumn(name = "original_id", nullable = true)
@org.hibernate.annotations.AccessType("field")
public OriginalImageDescriptor getOriginal() {
    return original;
}

From source file:org.projectforge.access.GroupTaskAccessDO.java

@ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE })
@JoinColumn(name = "group_id")
public GroupDO getGroup() {
    return group;
}

From source file:org.projectforge.access.GroupTaskAccessDO.java

@ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE }, targetEntity = TaskDO.class)
@JoinColumn(name = "task_id")
public TaskDO getTask() {
    return task;
}