Java Code Examples for javax.persistence.CascadeType

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project Core_2, under directory /javaee-impl/src/main/java/org/jboss/forge/spec/javaee/jpa/.

Source file: FieldPlugin.java

  21 
vote

@Command(value="oneToMany",help="Add a one-to-many relationship field (java.lang.Set<?>) to an existing @Entity class") public void newOneToManyRelationship(@Option(name="named",required=true,description="The field name",type=PromptType.JAVA_VARIABLE_NAME) final String fieldName,@Option(name="fieldType",required=true,description="The @Entity representing the 'many' side of the relationship.",type=PromptType.JAVA_CLASS) final String fieldType,@Option(name="inverseFieldName",required=false,description="Create an bi-directional relationship, using this value as the name of the inverse field.",type=PromptType.JAVA_VARIABLE_NAME) final String inverseFieldName){
  JavaSourceFacet java=project.getFacet(JavaSourceFacet.class);
  try {
    JavaClass one=getJavaClass();
    JavaClass many=findEntity(fieldType);
    one.addImport(Set.class);
    one.addImport(HashSet.class);
    one.addImport(many.getQualifiedName());
    Field<JavaClass> oneField=one.addField("private Set<" + many.getName() + "> "+ fieldName+ "= new HashSet<"+ many.getName()+ ">();");
    Annotation<JavaClass> annotation=oneField.addAnnotation(OneToMany.class);
    Refactory.createGetterAndSetter(one,oneField);
    if ((inverseFieldName != null) && !inverseFieldName.isEmpty()) {
      annotation.setStringValue("mappedBy",inverseFieldName);
      annotation.setLiteralValue("cascade","CascadeType.ALL");
      annotation.getOrigin().addImport(CascadeType.class);
      annotation.setLiteralValue("orphanRemoval","true");
      many.addImport(one);
      Field<JavaClass> manyField=many.addField("private " + one.getName() + " "+ inverseFieldName+ ";");
      manyField.addAnnotation(ManyToOne.class);
      Refactory.createGetterAndSetter(many,manyField);
      java.saveJavaSource(many);
    }
    java.saveJavaSource(one);
  }
 catch (  FileNotFoundException e) {
    shell.println("Could not locate the @Entity requested. No update was made.");
  }
}
 

Example 2

From project Core_2, under directory /javaee-impl/src/main/java/org/jboss/forge/spec/javaee/jpa/.

Source file: FieldPlugin.java

  19 
vote

@Command(value="manyToOne",help="Add a many-to-one relationship field to an existing @Entity class") public void newManyToOneRelationship(@Option(name="named",required=true,description="The field name",type=PromptType.JAVA_VARIABLE_NAME) final String fieldName,@Option(name="fieldType",required=true,description="The @Entity representing the 'one' side of the relationship.",type=PromptType.JAVA_CLASS) final String fieldType,@Option(name="inverseFieldName",required=false,description="Create an bi-directional relationship, using this value as the name of the inverse field.",type=PromptType.JAVA_VARIABLE_NAME) final String inverseFieldName){
  JavaSourceFacet java=project.getFacet(JavaSourceFacet.class);
  try {
    JavaClass many=getJavaClass();
    JavaClass one=findEntity(fieldType);
    many.addImport(one);
    Field<JavaClass> manyField=many.addField("private " + one.getName() + " "+ fieldName+ ";");
    manyField.addAnnotation(ManyToOne.class);
    Refactory.createGetterAndSetter(many,manyField);
    if ((inverseFieldName != null) && !inverseFieldName.isEmpty()) {
      one.addImport(Set.class);
      one.addImport(HashSet.class);
      one.addImport(many.getQualifiedName());
      Field<JavaClass> oneField=one.addField("private Set<" + many.getName() + "> "+ inverseFieldName+ "= new HashSet<"+ many.getName()+ ">();");
      Annotation<JavaClass> oneAnnotation=oneField.addAnnotation(OneToMany.class).setStringValue("mappedBy",fieldName);
      oneAnnotation.setLiteralValue("cascade","CascadeType.ALL");
      oneAnnotation.getOrigin().addImport(CascadeType.class);
      Refactory.createGetterAndSetter(one,oneField);
      java.saveJavaSource(one);
    }
    java.saveJavaSource(many);
  }
 catch (  FileNotFoundException e) {
    shell.println("Could not locate the @Entity requested. No update was made.");
  }
}
 

Example 3

From project Core_2, under directory /scaffold-faces/src/main/java/org/jboss/forge/scaffold/faces/.

Source file: FacesScaffold.java

  19 
vote

protected void createInitializers(final JavaClass entity){
  for (  Field<JavaClass> field : entity.getFields()) {
    if (field.hasAnnotation(OneToOne.class)) {
      Annotation<JavaClass> oneToOne=field.getAnnotation(OneToOne.class);
      if (oneToOne.getStringValue("mappedBy") == null && oneToOne.getStringValue("cascade") == null) {
        oneToOne.setEnumValue("cascade",CascadeType.ALL);
      }
      String methodName="new" + field.getTypeInspector().getName();
      if (!entity.hasMethodSignature(methodName)) {
        entity.addMethod().setName(methodName).setReturnTypeVoid().setPublic().setBody("this." + field.getName() + " = new "+ field.getType()+ "();");
      }
    }
  }
  for (  Method<JavaClass> method : entity.getMethods()) {
    if (method.hasAnnotation(OneToOne.class)) {
      Annotation<JavaClass> oneToOne=method.getAnnotation(OneToOne.class);
      if (oneToOne.getStringValue("mappedBy") == null && oneToOne.getStringValue("cascade") == null) {
        oneToOne.setEnumValue("cascade",CascadeType.ALL);
      }
      String methodName="new" + method.getReturnTypeInspector().getName();
      if (!entity.hasMethodSignature(methodName)) {
        entity.addMethod().setName(methodName).setReturnTypeVoid().setPublic().setBody("this." + method.getName() + " = new "+ method.getReturnType()+ "();");
      }
    }
  }
}
 

Example 4

From project Empire, under directory /core/src/com/clarkparsia/empire/util/.

Source file: BeanReflectUtil.java

  19 
vote

/** 
 * Return all  {@link CascadeType CascadeTypes} specified for the provided accessor.  If the access is not a Fieldor Method, or if it does not have any of the value multiplicity annotations ( {@link OneToOne},  {@link OneToMany}, {@link ManyToOne},  {@link OneToOne}, or  {@link ManyToMany}) this will return false, otherwise it will collect the values of the casade property of any of the aforementioned annotations used on the accessor.
 * @param theAccessor the accessor to inspect
 * @return the collection of CascadeTypes specified, or an empty list if none is specified.
 */
private static Collection<CascadeType> getCascadeTypes(Object theAccessor){
  Collection<CascadeType> aCascade=new HashSet<CascadeType>();
  if (theAccessor instanceof AccessibleObject) {
    AccessibleObject aObject=(AccessibleObject)theAccessor;
    if (aObject.getAnnotation(OneToMany.class) != null) {
      aCascade.addAll(Arrays.asList(aObject.getAnnotation(OneToMany.class).cascade()));
    }
 else     if (aObject.getAnnotation(OneToOne.class) != null) {
      aCascade.addAll(Arrays.asList(aObject.getAnnotation(OneToOne.class).cascade()));
    }
 else     if (aObject.getAnnotation(ManyToOne.class) != null) {
      aCascade.addAll(Arrays.asList(aObject.getAnnotation(ManyToOne.class).cascade()));
    }
 else     if (aObject.getAnnotation(ManyToMany.class) != null) {
      aCascade.addAll(Arrays.asList(aObject.getAnnotation(ManyToMany.class).cascade()));
    }
  }
  return aCascade;
}
 

Example 5

From project grails-data-mapping, under directory /grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/engine/.

Source file: NativeEntryEntityPersister.java

  19 
vote

/** 
 * Delete collections before owner delete.
 */
protected void cascadeBeforeDelete(PersistentEntity persistentEntity,EntityAccess entityAccess,K key,Object instance){
  List<PersistentProperty> props=persistentEntity.getPersistentProperties();
  for (  PersistentProperty prop : props) {
    String propertyKey=getPropertyKey(prop);
    if (prop instanceof OneToMany) {
      OneToMany oneToMany=(OneToMany)prop;
      if (oneToMany.isOwningSide() && oneToMany.doesCascade(CascadeType.REMOVE)) {
        Object propValue=entityAccess.getProperty(oneToMany.getName());
        if (propValue instanceof Collection) {
          cascadeDeleteCollection((Collection)propValue);
        }
      }
    }
 else     if (prop instanceof ManyToMany) {
      ManyToMany manyToMany=(ManyToMany)prop;
      if (manyToMany.isOwningSide() && manyToMany.doesCascade(CascadeType.REMOVE)) {
        Object propValue=entityAccess.getProperty(manyToMany.getName());
        if (propValue instanceof Collection) {
          cascadeDeleteCollection((Collection)propValue);
        }
      }
    }
  }
}
 

Example 6

From project grails-data-mapping, under directory /grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/engine/.

Source file: NativeEntryEntityPersister.java

  19 
vote

/** 
 * Delete many-to-ones after owner delete.
 */
protected void cascadeAfterDelete(PersistentEntity persistentEntity,EntityAccess entityAccess,K key,Object instance){
  List<PersistentProperty> props=persistentEntity.getPersistentProperties();
  for (  PersistentProperty prop : props) {
    String propertyKey=getPropertyKey(prop);
    if (prop instanceof Basic) {
      Object propValue=entityAccess.getProperty(prop.getName());
    }
 else     if (prop instanceof OneToMany) {
      OneToMany oneToMany=(OneToMany)prop;
      if (oneToMany.isOwningSide() && oneToMany.doesCascade(CascadeType.REMOVE)) {
        Object propValue=entityAccess.getProperty(oneToMany.getName());
        if (propValue instanceof Collection) {
          cascadeDeleteCollection((Collection)propValue);
        }
      }
    }
 else     if (prop instanceof ToOne) {
      ToOne association=(ToOne)prop;
      if (!(prop instanceof Embedded) && !(prop instanceof EmbeddedCollection) && association.doesCascade(CascadeType.REMOVE)) {
        if (association.isOwningSide()) {
          Object value=entityAccess.getProperty(association.getName());
          if (value != null) {
            Persister persister=session.getPersister(value);
            if (persister != null)             persister.delete(value);
          }
        }
      }
    }
  }
}
 

Example 7

From project grails-data-mapping, under directory /grails-datastore-core/src/main/groovy/org/grails/datastore/mapping/engine/.

Source file: NativeEntryEntityPersister.java

  19 
vote

private void updateToManyIndices(T nativeEntry,Object identifier,Map<Association,List<Serializable>> toManyKeys){
  for (  Association association : toManyKeys.keySet()) {
    if (association.doesCascade(CascadeType.PERSIST)) {
      final AssociationIndexer indexer=getAssociationIndexer(nativeEntry,association);
      if (indexer != null) {
        indexer.index(identifier,toManyKeys.get(association));
      }
    }
  }
}
 

Example 8

From project jBilling, under directory /src/java/com/sapienter/jbilling/server/user/contact/db/.

Source file: ContactDTO.java

  19 
vote

@OneToMany(cascade=CascadeType.ALL,fetch=FetchType.LAZY,mappedBy="contact") public Set<ContactFieldDTO> getFields(){
  if (fields == null) {
    fields=new HashSet<ContactFieldDTO>(0);
  }
  return this.fields;
}
 

Example 9

From project miso-lims, under directory /sqlstore/src/main/java/uk/ac/bbsrc/tgac/miso/sqlstore/.

Source file: SQLDilutionDAO.java

  19 
vote

@Transactional(readOnly=false,rollbackFor=Exception.class) @TriggersRemove(cacheName="libraryDilutionCache",[email protected](name="HashCodeCacheKeyGenerator",properties={@Property(name="includeMethod",value="false"),@Property(name="includeParameterTypes",value="false")})) public long saveLibraryDilution(LibraryDilution dilution) throws IOException {
  Long securityProfileId=dilution.getSecurityProfile().getProfileId();
  if (securityProfileId == null || (this.cascadeType != null)) {
    securityProfileId=securityProfileDAO.save(dilution.getSecurityProfile());
  }
  MapSqlParameterSource params=new MapSqlParameterSource();
  params.addValue("concentration",dilution.getConcentration()).addValue("library_libraryId",dilution.getLibrary().getLibraryId()).addValue("creationDate",dilution.getCreationDate()).addValue("securityProfile_profileId",securityProfileId).addValue("dilutionUserName",dilution.getDilutionCreator());
  if (dilution.getDilutionId() == AbstractDilution.UNSAVED_ID) {
    SimpleJdbcInsert insert=new SimpleJdbcInsert(template).withTableName("LibraryDilution").usingGeneratedKeyColumns("dilutionId");
    String name="LDI" + DbUtils.getAutoIncrement(template,"LibraryDilution");
    params.addValue("name",name);
    params.addValue("identificationBarcode",name + "::" + dilution.getLibrary().getAlias());
    Number newId=insert.executeAndReturnKey(params);
    dilution.setDilutionId(newId.longValue());
    dilution.setName(name);
  }
 else {
    params.addValue("dilutionId",dilution.getDilutionId()).addValue("name",dilution.getName()).addValue("identificationBarcode",dilution.getName() + "::" + dilution.getLibrary().getAlias());
    NamedParameterJdbcTemplate namedTemplate=new NamedParameterJdbcTemplate(template);
    namedTemplate.update(LIBRARY_DILUTION_UPDATE,params);
  }
  if (this.cascadeType != null) {
    Library l=dilution.getLibrary();
    if (this.cascadeType.equals(CascadeType.PERSIST)) {
      if (l != null)       libraryDAO.save(l);
    }
 else     if (this.cascadeType.equals(CascadeType.REMOVE)) {
      if (l != null) {
        Cache pc=cacheManager.getCache("libraryCache");
        pc.remove(DbUtils.hashCodeCacheKeyFor(l.getLibraryId()));
      }
    }
  }
  return dilution.getDilutionId();
}
 

Example 10

From project miso-lims, under directory /sqlstore/src/main/java/uk/ac/bbsrc/tgac/miso/sqlstore/.

Source file: SQLDilutionDAO.java

  19 
vote

@Transactional(readOnly=false,rollbackFor=IOException.class) @TriggersRemove(cacheName="emPCRDilutionCache",[email protected](name="HashCodeCacheKeyGenerator",properties={@Property(name="includeMethod",value="false"),@Property(name="includeParameterTypes",value="false")})) public long saveEmPCRDilution(emPCRDilution dilution) throws IOException {
  Long securityProfileId=dilution.getSecurityProfile().getProfileId();
  if (securityProfileId == null || (this.cascadeType != null)) {
    securityProfileId=securityProfileDAO.save(dilution.getSecurityProfile());
  }
  MapSqlParameterSource params=new MapSqlParameterSource();
  params.addValue("concentration",dilution.getConcentration()).addValue("emPCR_pcrId",dilution.getEmPCR().getPcrId()).addValue("creationDate",dilution.getCreationDate()).addValue("dilutionUserName",dilution.getDilutionCreator()).addValue("securityProfile_profileId",securityProfileId);
  if (dilution.getDilutionId() == AbstractDilution.UNSAVED_ID) {
    SimpleJdbcInsert insert=new SimpleJdbcInsert(template).withTableName("emPCRDilution").usingGeneratedKeyColumns("dilutionId");
    String name="EDI" + DbUtils.getAutoIncrement(template,"emPCRDilution");
    params.addValue("name",name);
    params.addValue("identificationBarcode",name + "::" + dilution.getEmPCR().getName());
    Number newId=insert.executeAndReturnKey(params);
    dilution.setDilutionId(newId.longValue());
    dilution.setName(name);
  }
 else {
    params.addValue("dilutionId",dilution.getDilutionId()).addValue("name",dilution.getName()).addValue("identificationBarcode",dilution.getName() + "::" + dilution.getEmPCR().getName());
    NamedParameterJdbcTemplate namedTemplate=new NamedParameterJdbcTemplate(template);
    namedTemplate.update(EMPCR_DILUTION_UPDATE,params);
  }
  if (this.cascadeType != null) {
    emPCR e=dilution.getEmPCR();
    if (this.cascadeType.equals(CascadeType.PERSIST)) {
      if (e != null)       emPcrDAO.save(e);
    }
 else     if (this.cascadeType.equals(CascadeType.REMOVE)) {
      if (e != null) {
        Cache pc=cacheManager.getCache("emPcrCache");
        pc.remove(DbUtils.hashCodeCacheKeyFor(e.getPcrId()));
      }
    }
  }
  return dilution.getDilutionId();
}
 

Example 11

From project miso-lims, under directory /sqlstore/src/main/java/uk/ac/bbsrc/tgac/miso/sqlstore/.

Source file: SQLDilutionDAO.java

  19 
vote

@Transactional(readOnly=false,rollbackFor=IOException.class) @TriggersRemove(cacheName="libraryDilutionCache",[email protected](name="HashCodeCacheKeyGenerator",properties={@Property(name="includeMethod",value="false"),@Property(name="includeParameterTypes",value="false")})) public boolean removeLibraryDilution(LibraryDilution d) throws IOException {
  NamedParameterJdbcTemplate namedTemplate=new NamedParameterJdbcTemplate(template);
  if (d.isDeletable() && (namedTemplate.update(LIBRARY_DILUTION_DELETE,new MapSqlParameterSource().addValue("dilutionId",d.getDilutionId())) == 1)) {
    Library l=d.getLibrary();
    if (this.cascadeType.equals(CascadeType.PERSIST)) {
      if (l != null)       libraryDAO.save(l);
    }
 else     if (this.cascadeType.equals(CascadeType.REMOVE)) {
      if (l != null) {
        Cache pc=cacheManager.getCache("libraryCache");
        pc.remove(DbUtils.hashCodeCacheKeyFor(l.getLibraryId()));
      }
    }
    return true;
  }
  return false;
}
 

Example 12

From project odata4j, under directory /odata4j-core/src/main/java/org/odata4j/producer/jpa/.

Source file: CreateAndLinkCommand.java

  19 
vote

@Override public boolean execute(JPAContext context){
  EdmNavigationProperty edmNavProperty=context.getEntity().getEdmEntitySet().getType().findNavigationProperty(context.getNavProperty());
  if (edmNavProperty == null || edmNavProperty.getToRole().getMultiplicity() != EdmMultiplicity.MANY) {
    throw new IllegalArgumentException("unknown navigation property " + context.getNavProperty() + " or navigation property toRole Multiplicity is not '*'");
  }
  EntityType<?> newJpaEntityType=context.getOtherEntity().getJPAEntityType();
  Object newJpaEntity=context.getOtherEntity().getJpaEntity();
  final String navProperty=context.getNavProperty();
  @SuppressWarnings({"unchecked","rawtypes"}) PluralAttribute<?,?,?> attr=Enumerable.create(context.getEntity().getJPAEntityType().getPluralAttributes()).firstOrNull(new Predicate1(){
    public boolean apply(    Object input){
      PluralAttribute<?,?,?> pa=(PluralAttribute<?,?,?>)input;
      return pa.getName().equals(navProperty);
    }
  }
);
  JPAMember member=JPAMember.create(attr,context.getEntity().getJpaEntity());
  Collection<Object> collection=member.get();
  collection.add(newJpaEntity);
  OneToMany oneToMany=member.getAnnotation(OneToMany.class);
  if (oneToMany != null && oneToMany.mappedBy() != null && !oneToMany.mappedBy().isEmpty()) {
    JPAMember.create(newJpaEntityType.getAttribute(oneToMany.mappedBy()),newJpaEntity).set(context.getEntity().getJpaEntity());
  }
  if (oneToMany != null && oneToMany.cascade() != null) {
    List<CascadeType> cascadeTypes=Arrays.asList(oneToMany.cascade());
    if (!cascadeTypes.contains(CascadeType.ALL) && !cascadeTypes.contains(CascadeType.PERSIST)) {
      context.getEntityManager().persist(newJpaEntity);
    }
  }
  context.setResult(JPAResults.entity(context.getOtherEntity().getJpaEntity()));
  return false;
}
 

Example 13

From project riot, under directory /content/src/org/riotfamily/components/model/.

Source file: ContentContainer.java

  19 
vote

@ManyToOne(fetch=FetchType.LAZY,cascade=CascadeType.ALL) @JoinColumn(name="preview_version") public Content getPreviewVersion(){
  if (previewVersion == null) {
    previewVersion=new Content(this);
  }
  return previewVersion;
}
 

Example 14

From project riot, under directory /content/src/org/riotfamily/components/model/.

Source file: ContentEntity.java

  19 
vote

@ManyToOne(cascade=CascadeType.ALL) public ContentContainer getContentContainer(){
  if (contentContainer == null) {
    contentContainer=new ContentContainer(this);
  }
  return contentContainer;
}
 

Example 15

From project riot, under directory /content/src/org/riotfamily/pages/model/.

Source file: Site.java

  19 
vote

@ManyToOne(fetch=FetchType.LAZY,cascade=CascadeType.ALL) public Content getProperties(){
  if (properties == null) {
    properties=new Content();
  }
  return properties;
}
 

Example 16

From project SeavusJB3, under directory /src/java/com/sapienter/jbilling/server/user/contact/db/.

Source file: ContactDTO.java

  19 
vote

@OneToMany(cascade=CascadeType.ALL,fetch=FetchType.LAZY,mappedBy="contact") public Set<ContactFieldDTO> getFields(){
  if (fields == null) {
    fields=new HashSet<ContactFieldDTO>(0);
  }
  return this.fields;
}
 

Example 17

From project zanata, under directory /zanata-model/src/main/java/org/zanata/model/.

Source file: HAccount.java

  19 
vote

@OneToMany(mappedBy="account",cascade={CascadeType.ALL}) @Cascade(value=org.hibernate.annotations.CascadeType.DELETE_ORPHAN) public Set<HCredentials> getCredentials(){
  if (credentials == null) {
    credentials=new HashSet<HCredentials>();
  }
  return credentials;
}
 

Example 18

From project zanata, under directory /zanata-model/src/main/java/org/zanata/model/.

Source file: HGlossaryEntry.java

  19 
vote

@OneToMany(cascade=CascadeType.ALL,mappedBy="glossaryEntry") @Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN) @MapKey(name="locale") public Map<HLocale,HGlossaryTerm> getGlossaryTerms(){
  if (glossaryTerms == null) {
    glossaryTerms=new HashMap<HLocale,HGlossaryTerm>();
  }
  return glossaryTerms;
}
 

Example 19

From project zanata, under directory /zanata-model/src/main/java/org/zanata/model/.

Source file: HGlossaryTerm.java

  19 
vote

@OneToMany(cascade=CascadeType.ALL) @Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN) @IndexColumn(name="pos",base=0,nullable=false) @JoinColumn(name="glossaryTermId",nullable=false) public List<HTermComment> getComments(){
  if (comments == null) {
    comments=new ArrayList<HTermComment>();
  }
  return comments;
}