Search in sources :

Example 11 with OneToMany

use of javax.persistence.OneToMany in project hibernate-orm by hibernate.

the class Ejb3XmlOneToManyTest method testCascadeAllPlusMore.

/**
	 * Make sure that it doesn't break the handler when {@link CascadeType#ALL}
	 * is specified in addition to a default cascade-persist or individual
	 * cascade settings.
	 */
@Test
public void testCascadeAllPlusMore() throws Exception {
    reader = getReader(Entity2.class, "field1", "one-to-many.orm22.xml");
    assertAnnotationPresent(OneToMany.class);
    OneToMany relAnno = reader.getAnnotation(OneToMany.class);
    assertEquals(6, relAnno.cascade().length);
    assertEquals(CascadeType.ALL, relAnno.cascade()[0]);
    assertEquals(CascadeType.PERSIST, relAnno.cascade()[1]);
    assertEquals(CascadeType.MERGE, relAnno.cascade()[2]);
    assertEquals(CascadeType.REMOVE, relAnno.cascade()[3]);
    assertEquals(CascadeType.REFRESH, relAnno.cascade()[4]);
    assertEquals(CascadeType.DETACH, relAnno.cascade()[5]);
}
Also used : OneToMany(javax.persistence.OneToMany) Test(org.junit.Test)

Example 12 with OneToMany

use of javax.persistence.OneToMany in project hibernate-orm by hibernate.

the class Ejb3XmlOneToManyTest method testAllAttributes.

@Test
public void testAllAttributes() throws Exception {
    reader = getReader(Entity2.class, "field1", "one-to-many.orm23.xml");
    assertAnnotationPresent(OneToMany.class);
    assertAnnotationNotPresent(OrderBy.class);
    assertAnnotationNotPresent(OrderColumn.class);
    assertAnnotationNotPresent(MapKey.class);
    assertAnnotationNotPresent(MapKeyClass.class);
    assertAnnotationNotPresent(MapKeyTemporal.class);
    assertAnnotationNotPresent(MapKeyEnumerated.class);
    assertAnnotationNotPresent(MapKeyColumn.class);
    assertAnnotationNotPresent(MapKeyJoinColumns.class);
    assertAnnotationNotPresent(MapKeyJoinColumn.class);
    assertAnnotationNotPresent(JoinTable.class);
    assertAnnotationNotPresent(JoinColumns.class);
    assertAnnotationNotPresent(JoinColumn.class);
    assertAnnotationPresent(Access.class);
    OneToMany relAnno = reader.getAnnotation(OneToMany.class);
    assertEquals(0, relAnno.cascade().length);
    assertEquals(FetchType.EAGER, relAnno.fetch());
    assertEquals("field2", relAnno.mappedBy());
    assertTrue(relAnno.orphanRemoval());
    assertEquals(Entity3.class, relAnno.targetEntity());
    assertEquals(AccessType.PROPERTY, reader.getAnnotation(Access.class).value());
}
Also used : OneToMany(javax.persistence.OneToMany) Test(org.junit.Test)

Example 13 with OneToMany

use of javax.persistence.OneToMany in project simplejpa by appoxy.

the class Save method persistOnly.

protected void persistOnly(Object o, String id) throws AmazonClientException, IllegalAccessException, InvocationTargetException, IOException {
    long start = System.currentTimeMillis();
    em.invokeEntityListener(o, newObject ? PrePersist.class : PreUpdate.class);
    AnnotationInfo ai = em.getFactory().getAnnotationManager().getAnnotationInfo(o);
    UpdateCondition expected = null;
    PersistentProperty versionField = null;
    Long nextVersion = -1L;
    String domainName;
    if (ai.getRootClass() != null) {
        domainName = em.getOrCreateDomain(ai.getRootClass());
    } else {
        domainName = em.getOrCreateDomain(o.getClass());
    }
    // Item item = DomainHelper.findItemById(this.em.getSimpleDb(),
    // domainName, id);
    // now set attributes
    List<ReplaceableAttribute> attsToPut = new ArrayList<ReplaceableAttribute>();
    List<Attribute> attsToDelete = new ArrayList<Attribute>();
    if (ai.getDiscriminatorValue() != null) {
        attsToPut.add(new ReplaceableAttribute(EntityManagerFactoryImpl.DTYPE, ai.getDiscriminatorValue(), true));
    }
    LazyInterceptor interceptor = null;
    if (o instanceof Factory) {
        Factory factory = (Factory) o;
        /*
             * for (Callback callback2 : factory.getCallbacks()) {
             * if(logger.isLoggable(Level.FINER)) logger.finer("callback=" +
             * callback2); if (callback2 instanceof LazyInterceptor) {
             * interceptor = (LazyInterceptor) callback2; } }
             */
        interceptor = (LazyInterceptor) factory.getCallback(0);
    }
    for (PersistentProperty field : ai.getPersistentProperties()) {
        Object ob = field.getProperty(o);
        String columnName = field.getColumnName();
        if (ob == null) {
            attsToDelete.add(new Attribute(columnName, null));
            continue;
        }
        if (field.isForeignKeyRelationship()) {
            // store the id of this object
            if (Collection.class.isAssignableFrom(field.getRawClass())) {
                for (Object each : (Collection) ob) {
                    String id2 = em.getId(each);
                    attsToPut.add(new ReplaceableAttribute(columnName, id2, true));
                }
            } else {
                String id2 = em.getId(ob);
                attsToPut.add(new ReplaceableAttribute(columnName, id2, true));
                /* check if we should persist this */
                boolean persistRelationship = false;
                ManyToOne a = field.getGetter().getAnnotation(ManyToOne.class);
                if (a != null && null != a.cascade()) {
                    CascadeType[] cascadeType = a.cascade();
                    for (CascadeType type : cascadeType) {
                        if (CascadeType.ALL == type || CascadeType.PERSIST == type) {
                            persistRelationship = true;
                        }
                    }
                }
                if (persistRelationship) {
                    em.persist(ob);
                }
            }
        } else if (field.isVersioned()) {
            Long curVersion = Long.parseLong("" + ob);
            nextVersion = (1 + curVersion);
            attsToPut.add(new ReplaceableAttribute(columnName, em.padOrConvertIfRequired(nextVersion), true));
            if (curVersion > 0) {
                expected = new UpdateCondition(columnName, em.padOrConvertIfRequired(curVersion), true);
            } else {
                expected = new UpdateCondition().withName(columnName).withExists(false);
            }
            versionField = field;
        } else if (field.isInverseRelationship()) {
            // FORCING BI-DIRECTIONAL RIGHT NOW SO JUST IGNORE
            // ... except for cascading persistence down to all items in the
            // OneToMany collection
            /* check if we should persist this */
            boolean persistRelationship = false;
            OneToMany a = field.getGetter().getAnnotation(OneToMany.class);
            CascadeType[] cascadeType = a.cascade();
            for (CascadeType type : cascadeType) {
                if (CascadeType.ALL == type || CascadeType.PERSIST == type) {
                    persistRelationship = true;
                }
            }
            if (persistRelationship) {
                if (ob instanceof Collection) {
                    // shouldn't it?
                    for (Object _item : (Collection) ob) {
                        // persist each item in the collection
                        em.persist(_item);
                    }
                }
            }
        } else if (field.isLob()) {
            // store in s3
            AmazonS3 s3 = null;
            // todo: need to make sure we only store to S3 if it's changed,
            // too slow.
            logger.fine("putting lob to s3");
            long start3 = System.currentTimeMillis();
            s3 = em.getS3Service();
            String bucketName = em.getS3BucketName();
            String s3ObjectId = id + "-" + field.getFieldName();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(bos);
            out.writeObject(ob);
            byte[] contentBytes = bos.toByteArray();
            out.close();
            InputStream input = new ByteArrayInputStream(contentBytes);
            s3.putObject(bucketName, s3ObjectId, input, null);
            em.statsS3Put(System.currentTimeMillis() - start3);
            logger.finer("setting lobkeyattribute=" + columnName + " - " + s3ObjectId);
            attsToPut.add(new ReplaceableAttribute(columnName, s3ObjectId, true));
        } else if (field.getEnumType() != null) {
            String toSet = getEnumValue(field, o);
            attsToPut.add(new ReplaceableAttribute(columnName, toSet, true));
        } else if (field.isId()) {
            continue;
        } else if (Collection.class.isInstance(ob)) {
            for (Object each : ((Collection) ob)) {
                String toSet = each != null ? em.padOrConvertIfRequired(each) : "";
                // todo: throw an exception if this is going to exceed
                // maximum size, suggest using @Lob
                attsToPut.add(new ReplaceableAttribute(columnName, toSet, true));
            }
        } else {
            String toSet = ob != null ? em.padOrConvertIfRequired(ob) : "";
            // todo: throw an exception if this is going to exceed maximum
            // size, suggest using @Lob
            attsToPut.add(new ReplaceableAttribute(columnName, toSet, true));
        }
    }
    // Now finally send it for storage (If have attributes to add)
    long start2 = System.currentTimeMillis();
    long duration2;
    if (!attsToPut.isEmpty()) {
        this.em.getSimpleDb().putAttributes(new PutAttributesRequest().withDomainName(domainName).withItemName(id).withAttributes(attsToPut).withExpected(expected));
        duration2 = System.currentTimeMillis() - start2;
        if (logger.isLoggable(Level.FINE))
            logger.fine("putAttributes time=" + (duration2));
        em.statsAttsPut(attsToPut.size(), duration2);
        if (null != versionField)
            versionField.setProperty(o, nextVersion);
    }
    /*
         * Check for nulled attributes so we can send a delete call. Don't
         * delete attributes if this is a new object AND don't delete atts if
         * it's not dirty AND don't delete if no nulls were set (nulledField on
         * LazyInterceptor)
         */
    if (interceptor != null) {
        if (interceptor.getNulledFields() != null && interceptor.getNulledFields().size() > 0) {
            List<Attribute> attsToDelete2 = new ArrayList<Attribute>();
            for (String s : interceptor.getNulledFields().keySet()) {
                String columnName = ai.getPersistentProperty(s).getColumnName();
                attsToDelete2.add(new Attribute(columnName, null));
            }
            start2 = System.currentTimeMillis();
            this.em.getSimpleDb().deleteAttributes(new DeleteAttributesRequest().withDomainName(domainName).withItemName(id).withAttributes(attsToDelete2));
            // todo: what about lobs? need to delete from s3
            duration2 = System.currentTimeMillis() - start2;
            logger.fine("deleteAttributes time=" + (duration2));
            em.statsAttsDeleted(attsToDelete2.size(), duration2);
        } else {
            logger.fine("deleteAttributes time= no nulled fields, nothing to delete.");
        }
    } else {
        if (!newObject && attsToDelete.size() > 0) {
            // not enhanced, but still have to deal with deleted attributes
            start2 = System.currentTimeMillis();
            // for (ItemAttribute itemAttribute : attsToDelete) {
            // System.out.println("itemAttr=" + itemAttribute.getName() +
            // ": " + itemAttribute.getValue());
            // }
            this.em.getSimpleDb().deleteAttributes(new DeleteAttributesRequest().withDomainName(domainName).withItemName(id).withAttributes(attsToDelete));
            // todo: what about lobs? need to delete from s3
            duration2 = System.currentTimeMillis() - start2;
            logger.fine("deleteAttributes time=" + (duration2));
            em.statsAttsDeleted(attsToDelete.size(), duration2);
        }
    }
    if (interceptor != null) {
        // reset the interceptor since we're all synced with the db now
        interceptor.reset();
    }
    em.invokeEntityListener(o, newObject ? PostPersist.class : PostUpdate.class);
    if (logger.isLoggable(Level.FINE))
        logger.fine("persistOnly time=" + (System.currentTimeMillis() - start));
}
Also used : AmazonS3(com.amazonaws.services.s3.AmazonS3) Attribute(com.amazonaws.services.simpledb.model.Attribute) ReplaceableAttribute(com.amazonaws.services.simpledb.model.ReplaceableAttribute) ArrayList(java.util.ArrayList) Factory(net.sf.cglib.proxy.Factory) PersistentProperty(com.spaceprogram.simplejpa.PersistentProperty) ObjectOutputStream(java.io.ObjectOutputStream) ManyToOne(javax.persistence.ManyToOne) PreUpdate(javax.persistence.PreUpdate) ReplaceableAttribute(com.amazonaws.services.simpledb.model.ReplaceableAttribute) PostUpdate(javax.persistence.PostUpdate) PrePersist(javax.persistence.PrePersist) DeleteAttributesRequest(com.amazonaws.services.simpledb.model.DeleteAttributesRequest) LazyInterceptor(com.spaceprogram.simplejpa.LazyInterceptor) UpdateCondition(com.amazonaws.services.simpledb.model.UpdateCondition) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) PostPersist(javax.persistence.PostPersist) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OneToMany(javax.persistence.OneToMany) ByteArrayInputStream(java.io.ByteArrayInputStream) CascadeType(javax.persistence.CascadeType) Collection(java.util.Collection) PutAttributesRequest(com.amazonaws.services.simpledb.model.PutAttributesRequest) AnnotationInfo(com.spaceprogram.simplejpa.AnnotationInfo)

Example 14 with OneToMany

use of javax.persistence.OneToMany in project hibernate-orm by hibernate.

the class Ejb3XmlOneToManyTest method testCascadeSomeWithDefaultPersist.

@Test
public void testCascadeSomeWithDefaultPersist() throws Exception {
    reader = getReader(Entity2.class, "field1", "one-to-many.orm21.xml");
    assertAnnotationPresent(OneToMany.class);
    OneToMany relAnno = reader.getAnnotation(OneToMany.class);
    assertEquals(4, relAnno.cascade().length);
    assertEquals(CascadeType.REMOVE, relAnno.cascade()[0]);
    assertEquals(CascadeType.REFRESH, relAnno.cascade()[1]);
    assertEquals(CascadeType.DETACH, relAnno.cascade()[2]);
    assertEquals(CascadeType.PERSIST, relAnno.cascade()[3]);
}
Also used : OneToMany(javax.persistence.OneToMany) Test(org.junit.Test)

Example 15 with OneToMany

use of javax.persistence.OneToMany in project hibernate-orm by hibernate.

the class JPAOverriddenAnnotationReader method overridesDefaultsInJoinTable.

private JoinTable overridesDefaultsInJoinTable(Annotation annotation, XMLContext.Default defaults) {
    //no element but might have some default or some annotation
    boolean defaultToJoinTable = !(isPhysicalAnnotationPresent(JoinColumn.class) || isPhysicalAnnotationPresent(JoinColumns.class));
    final Class<? extends Annotation> annotationClass = annotation.annotationType();
    defaultToJoinTable = defaultToJoinTable && ((annotationClass == ManyToMany.class && StringHelper.isEmpty(((ManyToMany) annotation).mappedBy())) || (annotationClass == OneToMany.class && StringHelper.isEmpty(((OneToMany) annotation).mappedBy())) || (annotationClass == ElementCollection.class));
    final Class<JoinTable> annotationType = JoinTable.class;
    if (defaultToJoinTable && (StringHelper.isNotEmpty(defaults.getCatalog()) || StringHelper.isNotEmpty(defaults.getSchema()))) {
        AnnotationDescriptor ad = new AnnotationDescriptor(annotationType);
        if (defaults.canUseJavaAnnotations()) {
            JoinTable table = getPhysicalAnnotation(annotationType);
            if (table != null) {
                ad.setValue("name", table.name());
                ad.setValue("schema", table.schema());
                ad.setValue("catalog", table.catalog());
                ad.setValue("uniqueConstraints", table.uniqueConstraints());
                ad.setValue("joinColumns", table.joinColumns());
                ad.setValue("inverseJoinColumns", table.inverseJoinColumns());
            }
        }
        if (StringHelper.isEmpty((String) ad.valueOf("schema")) && StringHelper.isNotEmpty(defaults.getSchema())) {
            ad.setValue("schema", defaults.getSchema());
        }
        if (StringHelper.isEmpty((String) ad.valueOf("catalog")) && StringHelper.isNotEmpty(defaults.getCatalog())) {
            ad.setValue("catalog", defaults.getCatalog());
        }
        return AnnotationFactory.create(ad);
    } else if (defaults.canUseJavaAnnotations()) {
        return getPhysicalAnnotation(annotationType);
    } else {
        return null;
    }
}
Also used : AnnotationDescriptor(org.hibernate.annotations.common.annotationfactory.AnnotationDescriptor) PrimaryKeyJoinColumn(javax.persistence.PrimaryKeyJoinColumn) MapKeyJoinColumn(javax.persistence.MapKeyJoinColumn) JoinColumn(javax.persistence.JoinColumn) MapKeyJoinColumns(javax.persistence.MapKeyJoinColumns) JoinColumns(javax.persistence.JoinColumns) PrimaryKeyJoinColumns(javax.persistence.PrimaryKeyJoinColumns) ManyToMany(javax.persistence.ManyToMany) ElementCollection(javax.persistence.ElementCollection) OneToMany(javax.persistence.OneToMany) JoinTable(javax.persistence.JoinTable)

Aggregations

OneToMany (javax.persistence.OneToMany)21 ManyToMany (javax.persistence.ManyToMany)10 ManyToOne (javax.persistence.ManyToOne)8 JoinColumn (javax.persistence.JoinColumn)7 OneToOne (javax.persistence.OneToOne)7 Field (java.lang.reflect.Field)6 JoinTable (javax.persistence.JoinTable)6 ReflectUtil (org.eweb4j.util.ReflectUtil)5 Method (java.lang.reflect.Method)4 Test (org.junit.Test)4 ArrayList (java.util.ArrayList)3 Column (javax.persistence.Column)3 ElementCollection (javax.persistence.ElementCollection)3 JoinColumns (javax.persistence.JoinColumns)3 AssertionFailure (org.hibernate.annotations.common.AssertionFailure)3 HashMap (java.util.HashMap)2 FetchType (javax.persistence.FetchType)2 DAOException (org.eweb4j.orm.dao.DAOException)2 AnnotationException (org.hibernate.AnnotationException)2 MappingException (org.hibernate.MappingException)2