protected void applyCacheSettings(Configuration configuration) {
   if (getCacheConcurrencyStrategy() != null) {
     Iterator itr = configuration.getClassMappings();
     while (itr.hasNext()) {
       PersistentClass clazz = (PersistentClass) itr.next();
       Iterator props = clazz.getPropertyClosureIterator();
       boolean hasLob = false;
       while (props.hasNext()) {
         Property prop = (Property) props.next();
         if (prop.getValue().isSimpleValue()) {
           String type = ((SimpleValue) prop.getValue()).getTypeName();
           if ("blob".equals(type) || "clob".equals(type)) {
             hasLob = true;
           }
           if (Blob.class.getName().equals(type) || Clob.class.getName().equals(type)) {
             hasLob = true;
           }
         }
       }
       if (!hasLob && !clazz.isInherited() && overrideCacheStrategy()) {
         configuration.setCacheConcurrencyStrategy(
             clazz.getEntityName(), getCacheConcurrencyStrategy());
       }
     }
     itr = configuration.getCollectionMappings();
     while (itr.hasNext()) {
       Collection coll = (Collection) itr.next();
       configuration.setCollectionCacheConcurrencyStrategy(
           coll.getRole(), getCacheConcurrencyStrategy());
     }
   }
 }
  public void testForeignKeyColumnBinding() {
    GroovyClassLoader cl = new GroovyClassLoader();
    GrailsDomainClass oneClass =
        new DefaultGrailsDomainClass(
            cl.parseClass(
                "class TestOneSide {\n"
                    + "    Long id \n"
                    + "    Long version \n"
                    + "    String name \n"
                    + "    String description \n"
                    + "}"));
    GrailsDomainClass domainClass =
        new DefaultGrailsDomainClass(
            cl.parseClass(
                "class TestManySide {\n"
                    + "    Long id \n"
                    + "    Long version \n"
                    + "    String name \n"
                    + "    TestOneSide testOneSide \n"
                    + "\n"
                    + "    static mapping = {\n"
                    + "        columns {\n"
                    + "            testOneSide column:'EXPECTED_COLUMN_NAME'"
                    + "        }\n"
                    + "    }\n"
                    + "}"));

    DefaultGrailsDomainConfiguration config =
        getDomainConfig(cl, new Class[] {oneClass.getClazz(), domainClass.getClazz()});

    PersistentClass persistentClass = config.getClassMapping("TestManySide");

    Column column = (Column) persistentClass.getProperty("testOneSide").getColumnIterator().next();
    assertEquals("EXPECTED_COLUMN_NAME", column.getName());
  }
 private <X> void applyIdMetadata(
     PersistentClass persistentClass, EntityTypeImpl<X> jpaEntityType) {
   if (persistentClass.hasIdentifierProperty()) {
     final Property declaredIdentifierProperty = persistentClass.getDeclaredIdentifierProperty();
     if (declaredIdentifierProperty != null) {
       jpaEntityType
           .getBuilder()
           .applyIdAttribute(
               attributeFactory.buildIdAttribute(jpaEntityType, declaredIdentifierProperty));
     }
   } else if (persistentClass.hasIdentifierMapper()) {
     @SuppressWarnings("unchecked")
     Iterator<Property> propertyIterator =
         persistentClass.getIdentifierMapper().getPropertyIterator();
     Set<SingularAttribute<? super X, ?>> attributes =
         buildIdClassAttributes(jpaEntityType, propertyIterator);
     jpaEntityType.getBuilder().applyIdClassAttributes(attributes);
   } else {
     final KeyValue value = persistentClass.getIdentifier();
     if (value instanceof Component) {
       final Component component = (Component) value;
       if (component.getPropertySpan() > 1) {
         // FIXME we are an Hibernate embedded id (ie not type)
       } else {
         // FIXME take care of declared vs non declared property
         jpaEntityType
             .getBuilder()
             .applyIdAttribute(
                 attributeFactory.buildIdAttribute(
                     jpaEntityType, (Property) component.getPropertyIterator().next()));
       }
     }
   }
 }
  public ClassAuditingData getAuditData() {
    if (pc.getClassName() == null) {
      return auditData;
    }

    try {
      XClass xclass = reflectionManager.classForName(pc.getClassName(), this.getClass());

      ModificationStore defaultStore = getDefaultAudited(xclass);
      if (defaultStore != null) {
        auditData.setDefaultAudited(true);
      }

      new AuditedPropertiesReader(
              defaultStore,
              new PersistentClassPropertiesSource(xclass),
              auditData,
              globalCfg,
              reflectionManager,
              "")
          .read();

      addAuditTable(xclass);
      addAuditSecondaryTables(xclass);
    } catch (ClassNotFoundException e) {
      throw new MappingException(e);
    }

    return auditData;
  }
  public static GroovyAwareJavassistProxyFactory buildProxyFactory(
      PersistentClass persistentClass) {
    GroovyAwareJavassistProxyFactory proxyFactory = new GroovyAwareJavassistProxyFactory();

    @SuppressWarnings("unchecked")
    Set<Class<HibernateProxy>> proxyInterfaces = new HashSet<Class<HibernateProxy>>();
    proxyInterfaces.add(HibernateProxy.class);

    final Class<?> javaClass = persistentClass.getMappedClass();
    final Property identifierProperty = persistentClass.getIdentifierProperty();
    final Method idGetterMethod =
        identifierProperty != null ? identifierProperty.getGetter(javaClass).getMethod() : null;
    final Method idSetterMethod =
        identifierProperty != null ? identifierProperty.getSetter(javaClass).getMethod() : null;
    final Type identifierType =
        persistentClass.hasEmbeddedIdentifier() ? persistentClass.getIdentifier().getType() : null;

    try {
      proxyFactory.postInstantiate(
          persistentClass.getEntityName(),
          javaClass,
          proxyInterfaces,
          idGetterMethod,
          idSetterMethod,
          identifierType instanceof CompositeType ? (CompositeType) identifierType : null);
    } catch (HibernateException e) {
      LOG.warn("Cannot instantiate proxy factory: " + e.getMessage());
      return null;
    }

    return proxyFactory;
  }
Пример #6
0
  // bind collections.
  private void bindIncomingForeignKeys(
      PersistentClass rc, Set processed, List foreignKeys, Mapping mapping) {
    if (foreignKeys != null) {
      for (Iterator iter = foreignKeys.iterator(); iter.hasNext(); ) {
        ForeignKey foreignKey = (ForeignKey) iter.next();

        if (revengStrategy.excludeForeignKeyAsCollection(
            foreignKey.getName(),
            TableIdentifier.create(foreignKey.getTable()),
            foreignKey.getColumns(),
            TableIdentifier.create(foreignKey.getReferencedTable()),
            foreignKey.getReferencedColumns())) {
          log.debug(
              "Rev.eng excluded one-to-many or one-to-one for foreignkey " + foreignKey.getName());
        } else if (revengStrategy.isOneToOne(foreignKey)) {
          Property property =
              bindOneToOne(rc, foreignKey.getTable(), foreignKey, processed, false, true);
          rc.addProperty(property);
        } else {
          Property property = bindOneToMany(rc, foreignKey, processed, mapping);
          rc.addProperty(property);
        }
      }
    }
  }
  public void testInsertableUpdateableHibernateMapping() throws Exception {
    GroovyClassLoader cl = new GroovyClassLoader();
    GrailsDomainClass domainClass =
        new DefaultGrailsDomainClass(
            cl.parseClass(
                "class TestInsertableUpdateableDomain {\n"
                    + "    Long id \n"
                    + "    Long version \n"
                    + "    String testString1 \n"
                    + "    String testString2 \n"
                    + "\n"
                    + "    static mapping = {\n"
                    + "       testString1 insertable:false, updateable:false \n"
                    + "       testString2 updateable:false, insertable:false \n"
                    + "    }\n"
                    + "}"));

    DefaultGrailsDomainConfiguration config =
        getDomainConfig(cl, new Class[] {domainClass.getClazz()});

    PersistentClass persistentClass = config.getClassMapping("TestInsertableUpdateableDomain");

    Property property1 = persistentClass.getProperty("testString1");
    assertEquals(false, property1.isInsertable());
    assertEquals(false, property1.isUpdateable());

    Property property2 = persistentClass.getProperty("testString2");
    assertEquals(false, property2.isUpdateable());
    assertEquals(false, property2.isInsertable());
  }
 @Override
 public Class<? extends EntityPersister> getEntityPersisterClass(PersistentClass metadata) {
   // todo : make sure this is based on an attribute kept on the metamodel in the new code, not the
   // concrete PersistentClass impl found!
   if (RootClass.class.isInstance(metadata)) {
     if (metadata.hasSubclasses()) {
       // If the class has children, we need to find of which kind
       metadata = (PersistentClass) metadata.getDirectSubclasses().next();
     } else {
       return singleTableEntityPersister();
     }
   }
   if (JoinedSubclass.class.isInstance(metadata)) {
     return joinedSubclassEntityPersister();
   } else if (UnionSubclass.class.isInstance(metadata)) {
     return unionSubclassEntityPersister();
   } else if (SingleTableSubclass.class.isInstance(metadata)) {
     return singleTableEntityPersister();
   } else {
     throw new UnknownPersisterException(
         "Could not determine persister implementation for entity ["
             + metadata.getEntityName()
             + "]");
   }
 }
Пример #9
0
  private void buildSessionFactory(String[] files) throws Exception {

    if (getSessions() != null) getSessions().close();

    try {

      setCfg(new Configuration());

      cfg.addProperties(getExtraProperties());

      if (recreateSchema()) {
        cfg.setProperty(Environment.HBM2DDL_AUTO, "create-drop");
      }

      for (int i = 0; i < files.length; i++) {
        if (!files[i].startsWith("net/")) files[i] = getBaseForMappings() + files[i];
        getCfg().addResource(files[i], TestCase.class.getClassLoader());
      }

      setDialect(Dialect.getDialect());

      configure(cfg);

      if (getCacheConcurrencyStrategy() != null) {

        Iterator iter = cfg.getClassMappings();
        while (iter.hasNext()) {
          PersistentClass clazz = (PersistentClass) iter.next();
          Iterator props = clazz.getPropertyClosureIterator();
          boolean hasLob = false;
          while (props.hasNext()) {
            Property prop = (Property) props.next();
            if (prop.getValue().isSimpleValue()) {
              String type = ((SimpleValue) prop.getValue()).getTypeName();
              if ("blob".equals(type) || "clob".equals(type)) hasLob = true;
              if (Blob.class.getName().equals(type) || Clob.class.getName().equals(type))
                hasLob = true;
            }
          }
          if (!hasLob && !clazz.isInherited() && overrideCacheStrategy()) {
            cfg.setCacheConcurrencyStrategy(clazz.getEntityName(), getCacheConcurrencyStrategy());
          }
        }

        iter = cfg.getCollectionMappings();
        while (iter.hasNext()) {
          Collection coll = (Collection) iter.next();
          cfg.setCollectionCacheConcurrencyStrategy(coll.getRole(), getCacheConcurrencyStrategy());
        }
      }

      setSessions(getCfg().buildSessionFactory(/*new TestInterceptor()*/ ));

      afterSessionFactoryBuilt();
    } catch (Exception e) {
      e.printStackTrace();
      throw e;
    }
  }
 /** Constructor */
 public FeatureMapEntryInstantiator(PersistentClass pc) {
   AssertUtil.assertTrue(
       pc.getEntityName() + " does not have a meta attribute",
       pc.getMetaAttribute(HbMapperConstants.FEATUREMAP_META) != null);
   log.debug("Creating fme instantiator for " + pc.getEntityName());
   proxyInterface = pc.getProxyInterface();
   persistentClass = pc;
 }
  public void testDefaultNamingStrategy() {

    GroovyClassLoader cl = new GroovyClassLoader();
    GrailsDomainClass oneClass =
        new DefaultGrailsDomainClass(
            cl.parseClass(
                "class TestOneSide {\n"
                    + "    Long id \n"
                    + "    Long version \n"
                    + "    String fooName \n"
                    + "    String barDescriPtion \n"
                    + "}"));
    GrailsDomainClass domainClass =
        new DefaultGrailsDomainClass(
            cl.parseClass(
                "class TestManySide {\n"
                    + "    Long id \n"
                    + "    Long version \n"
                    + "    TestOneSide testOneSide \n"
                    + "\n"
                    + "    static mapping = {\n"
                    + "        columns {\n"
                    + "            testOneSide column:'EXPECTED_COLUMN_NAME'"
                    + "        }\n"
                    + "    }\n"
                    + "}"));

    DefaultGrailsDomainConfiguration config =
        getDomainConfig(cl, new Class[] {oneClass.getClazz(), domainClass.getClazz()});

    PersistentClass persistentClass = config.getClassMapping("TestOneSide");
    assertEquals("test_one_side", persistentClass.getTable().getName());

    Column column = (Column) persistentClass.getProperty("id").getColumnIterator().next();
    assertEquals("id", column.getName());

    column = (Column) persistentClass.getProperty("version").getColumnIterator().next();
    assertEquals("version", column.getName());

    column = (Column) persistentClass.getProperty("fooName").getColumnIterator().next();
    assertEquals("foo_name", column.getName());

    column = (Column) persistentClass.getProperty("barDescriPtion").getColumnIterator().next();
    assertEquals("bar_descri_ption", column.getName());

    persistentClass = config.getClassMapping("TestManySide");
    assertEquals("test_many_side", persistentClass.getTable().getName());

    column = (Column) persistentClass.getProperty("id").getColumnIterator().next();
    assertEquals("id", column.getName());

    column = (Column) persistentClass.getProperty("version").getColumnIterator().next();
    assertEquals("version", column.getName());

    column = (Column) persistentClass.getProperty("testOneSide").getColumnIterator().next();
    assertEquals("EXPECTED_COLUMN_NAME", column.getName());
  }
  private static Constructor getConstructor(PersistentClass persistentClass) {
    if (persistentClass == null || !persistentClass.hasPojoRepresentation()) {
      return null;
    }

    try {
      return ReflectHelper.getDefaultConstructor(persistentClass.getMappedClass());
    } catch (Throwable t) {
      return null;
    }
  }
 public DynamicMapInstantiator(PersistentClass mappingInfo) {
   this.entityName = mappingInfo.getEntityName();
   isInstanceEntityNames.add(entityName);
   if (mappingInfo.hasSubclasses()) {
     Iterator itr = mappingInfo.getSubclassClosureIterator();
     while (itr.hasNext()) {
       final PersistentClass subclassInfo = (PersistentClass) itr.next();
       isInstanceEntityNames.add(subclassInfo.getEntityName());
     }
   }
 }
Пример #14
0
 public void popEntityWorkedOn(PersistentClass persistentClass) {
   final PersistentClass stackTop =
       stackOfPersistentClassesBeingProcessed.remove(
           stackOfPersistentClassesBeingProcessed.size() - 1);
   if (stackTop != persistentClass) {
     throw new AssertionFailure(
         "Inconsistent popping: "
             + persistentClass.getEntityName()
             + " instead of "
             + stackTop.getEntityName());
   }
 }
  public Dom4jInstantiator(PersistentClass mappingInfo) {
    this.nodeName = mappingInfo.getNodeName();
    isInstanceNodeNames.add(nodeName);

    if (mappingInfo.hasSubclasses()) {
      Iterator itr = mappingInfo.getSubclassClosureIterator();
      while (itr.hasNext()) {
        final PersistentClass subclassInfo = (PersistentClass) itr.next();
        isInstanceNodeNames.add(subclassInfo.getNodeName());
      }
    }
  }
  @Test
  public void testGeneratedUuidId() {
    StandardServiceRegistry ssr =
        new StandardServiceRegistryBuilder()
            .applySetting(AvailableSettings.HBM2DDL_AUTO, "create-drop")
            .build();
    try {
      Metadata metadata =
          new MetadataSources(ssr).addAnnotatedClass(TheEntity.class).buildMetadata();
      ((MetadataImpl) metadata).validate();

      PersistentClass entityBinding = metadata.getEntityBinding(TheEntity.class.getName());
      assertEquals(UUID.class, entityBinding.getIdentifier().getType().getReturnedClass());
      IdentifierGenerator generator =
          entityBinding
              .getIdentifier()
              .createIdentifierGenerator(
                  metadata.getIdentifierGeneratorFactory(),
                  metadata.getDatabase().getDialect(),
                  null,
                  null,
                  (RootClass) entityBinding);
      assertTyping(UUIDGenerator.class, generator);

      // now a functional test
      SessionFactory sf = metadata.buildSessionFactory();
      try {
        TheEntity theEntity = new TheEntity();

        Session s = sf.openSession();
        s.beginTransaction();
        s.save(theEntity);
        s.getTransaction().commit();
        s.close();

        assertNotNull(theEntity.id);

        s = sf.openSession();
        s.beginTransaction();
        s.delete(theEntity);
        s.getTransaction().commit();
        s.close();
      } finally {
        try {
          sf.close();
        } catch (Exception ignore) {
        }
      }
    } finally {
      StandardServiceRegistryBuilder.destroy(ssr);
    }
  }
  /**
   * @param cfg
   * @return iterator over all the IdentifierGenerator's found in the entitymodel and return a list
   *     of unique IdentifierGenerators
   * @throws MappingException
   */
  private Iterator iterateGenerators(Configuration cfg) throws MappingException {

    TreeMap generators = new TreeMap();
    String defaultCatalog = getSettings().getDefaultCatalogName();
    String defaultSchema = getSettings().getDefaultSchemaName();

    Iterator iter = cfg.getClassMappings();
    while (iter.hasNext()) {
      PersistentClass pc = (PersistentClass) iter.next();

      if (!pc.isInherited()) {

        IdentifierGenerator ig =
            pc.getIdentifier()
                .createIdentifierGenerator(
                    cfg.getIdentifierGeneratorFactory(),
                    dialect,
                    defaultCatalog,
                    defaultSchema,
                    (RootClass) pc);

        if (ig instanceof PersistentIdentifierGenerator) {
          generators.put(((PersistentIdentifierGenerator) ig).generatorKey(), ig);
        }
      }
    }

    iter = getConfiguration().getCollectionMappings();
    while (iter.hasNext()) {
      Collection collection = (Collection) iter.next();

      if (collection.isIdentified()) {

        IdentifierGenerator ig =
            ((IdentifierCollection) collection)
                .getIdentifier()
                .createIdentifierGenerator(
                    getConfiguration().getIdentifierGeneratorFactory(),
                    dialect,
                    defaultCatalog,
                    defaultSchema,
                    null);

        if (ig instanceof PersistentIdentifierGenerator) {
          generators.put(((PersistentIdentifierGenerator) ig).generatorKey(), ig);
        }
      }
    }

    return generators.values().iterator();
  }
Пример #18
0
  public void testDomainClassBinding() {
    GroovyClassLoader cl = new GroovyClassLoader();
    GrailsDomainClass domainClass =
        new DefaultGrailsDomainClass(
            cl.parseClass(
                "public class BinderTestClass {\n"
                    + "    Long id; \n"
                    + "    Long version; \n"
                    + "\n"
                    + "    String firstName; \n"
                    + "    String lastName; \n"
                    + "    String comment; \n"
                    + "    Integer age;\n"
                    + "    boolean active = true"
                    + "\n"
                    + "    static constraints = {\n"
                    + "        firstName(nullable:true,size:4..15)\n"
                    + "        lastName(nullable:false)\n"
                    + "        age(nullable:true)\n"
                    + "    }\n"
                    + "}"));

    DefaultGrailsDomainConfiguration config = getDomainConfig(cl, cl.getLoadedClasses());

    // Test database mappings
    PersistentClass persistentClass = config.getClassMapping("BinderTestClass");
    assertTrue(
        "Property [firstName] must be optional in db mapping",
        persistentClass.getProperty("firstName").isOptional());
    assertFalse(
        "Property [lastName] must be required in db mapping",
        persistentClass.getProperty("lastName").isOptional());
    // Property must be required by default
    assertFalse(
        "Property [comment] must be required in db mapping",
        persistentClass.getProperty("comment").isOptional());

    // Test properties
    assertTrue(
        "Property [firstName] must be optional",
        domainClass.getPropertyByName("firstName").isOptional());
    assertFalse(
        "Property [lastName] must be optional",
        domainClass.getPropertyByName("lastName").isOptional());
    assertFalse(
        "Property [comment] must be required",
        domainClass.getPropertyByName("comment").isOptional());
    assertTrue(
        "Property [age] must be optional", domainClass.getPropertyByName("age").isOptional());
  }
Пример #19
0
 @Test
 public void testDiscriminatorFormulaInAuditTable() {
   assert parentAudit.getDiscriminator().hasFormula();
   Iterator iterator = parentAudit.getDiscriminator().getColumnIterator();
   while (iterator.hasNext()) {
     Object o = iterator.next();
     if (o instanceof Formula) {
       Formula formula = (Formula) o;
       Assert.assertEquals(ParentEntity.DISCRIMINATOR_QUERY, formula.getText());
       return;
     }
   }
   assert false;
 }
Пример #20
0
  private String makeUnique(PersistentClass clazz, String propertyName) {
    List list = new ArrayList();

    if (clazz.hasIdentifierProperty()) {
      list.add(clazz.getIdentifierProperty());
    }

    if (clazz.isVersioned()) {
      list.add(clazz.getVersion());
    }

    JoinedIterator iterator =
        new JoinedIterator(list.iterator(), clazz.getPropertyClosureIterator());
    return makeUnique(iterator, propertyName);
  }
Пример #21
0
 /*package*/ void registerEntityType(
     PersistentClass persistentClass, EntityTypeImpl<?> entityType) {
   entityTypes.put(entityType.getBindableJavaType(), entityType);
   entityTypesByEntityName.put(persistentClass.getEntityName(), entityType);
   entityTypesByPersistentClass.put(persistentClass, entityType);
   orderedMappings.add(persistentClass);
 }
 @Override
 public boolean hasNext() {
   // we need to read the next non null one. getMappedClass() can return null and should be
   // ignored
   if (future != null) {
     return true;
   }
   do {
     if (!hibernatePersistentClassIterator.hasNext()) {
       future = null;
       return false;
     }
     final PersistentClass pc = hibernatePersistentClassIterator.next();
     future = pc.getMappedClass();
   } while (future == null);
   return true;
 }
 private String internalGetDBTableName(final Class<?> entity) {
   final String entityName = entity.getName();
   final PersistentClass persistentClass = configuration.getClassMapping(entityName);
   if (persistentClass == null) {
     final String msg =
         "Could not find persistent class for entityName '"
             + entityName
             + "' (OK for non hibernate objects).";
     if (entityName.endsWith("DO") == true) {
       log.error(msg);
     } else {
       log.info(msg);
     }
     return null;
   }
   return persistentClass.getTable().getName();
 }
  private String getMappedBy(Table collectionTable, PersistentClass referencedClass) {
    // If there's an @AuditMappedBy specified, returning it directly.
    String auditMappedBy = propertyAuditingData.getAuditMappedBy();
    if (auditMappedBy != null) {
      return auditMappedBy;
    }

    // searching in referenced class
    String mappedBy = this.searchMappedBy(referencedClass, collectionTable);

    // not found on referenced class, searching on superclasses
    if (mappedBy == null) {
      LOG.debugf(
          "Going to search the mapped by attribute for %s in superclasses of entity: %s",
          propertyName, referencedClass.getClassName());

      PersistentClass tempClass = referencedClass;
      while ((mappedBy == null) && (tempClass.getSuperclass() != null)) {
        LOG.debugf("Searching in superclass: %s", tempClass.getSuperclass().getClassName());
        mappedBy = this.searchMappedBy(tempClass.getSuperclass(), collectionTable);
        tempClass = tempClass.getSuperclass();
      }
    }

    if (mappedBy == null) {
      throw new MappingException(
          "Unable to read the mapped by attribute for "
              + propertyName
              + " in "
              + referencedClass.getClassName()
              + "!");
    }

    return mappedBy;
  }
Пример #25
0
 private EntityMetamodel getDeclarerEntityMetamodel(IdentifiableType<?> ownerType) {
   final Type.PersistenceType persistenceType = ownerType.getPersistenceType();
   if (persistenceType == Type.PersistenceType.ENTITY) {
     return context
         .getSessionFactory()
         .getEntityPersister(ownerType.getJavaType().getName())
         .getEntityMetamodel();
   } else if (persistenceType == Type.PersistenceType.MAPPED_SUPERCLASS) {
     PersistentClass persistentClass =
         context.getPersistentClassHostingProperties((MappedSuperclassTypeImpl<?>) ownerType);
     return context
         .getSessionFactory()
         .getEntityPersister(persistentClass.getClassName())
         .getEntityMetamodel();
   } else {
     throw new AssertionFailure(
         "Cannot get the metamodel for PersistenceType: " + persistenceType);
   }
 }
Пример #26
0
 private <X> void applyVersionAttribute(
     PersistentClass persistentClass, EntityTypeImpl<X> jpaEntityType) {
   final Property declaredVersion = persistentClass.getDeclaredVersion();
   if (declaredVersion != null) {
     jpaEntityType
         .getBuilder()
         .applyVersionAttribute(
             attributeFactory.buildVersionAttribute(jpaEntityType, declaredVersion));
   }
 }
  /**
   * Tests that single- and multi-column user type mappings work correctly. Also Checks that the
   * "sqlType" property is honoured.
   */
  public void testUserTypeMappings() {
    DefaultGrailsDomainConfiguration config = getDomainConfig(MULTI_COLUMN_USER_TYPE_DEFINITION);
    PersistentClass persistentClass = config.getClassMapping("Item");

    // First check the "name" property and its associated column.
    Property nameProperty = persistentClass.getProperty("name");
    assertEquals(1, nameProperty.getColumnSpan());
    assertEquals("name", nameProperty.getName());

    Column column = (Column) nameProperty.getColumnIterator().next();
    assertEquals("s_name", column.getName());
    assertEquals("text", column.getSqlType());

    // Next the "other" property.
    Property otherProperty = persistentClass.getProperty("other");
    assertEquals(1, otherProperty.getColumnSpan());
    assertEquals("other", otherProperty.getName());

    column = (Column) otherProperty.getColumnIterator().next();
    assertEquals("other", column.getName());
    assertEquals("wrapper-characters", column.getSqlType());
    assertEquals(MyUserType.class.getName(), column.getValue().getType().getName());
    assertTrue(column.getValue() instanceof SimpleValue);
    SimpleValue v = (SimpleValue) column.getValue();
    assertEquals("myParam1", v.getTypeParameters().get("param1"));
    assertEquals("myParam2", v.getTypeParameters().get("param2"));

    // And now for the "price" property, which should have two
    // columns.
    Property priceProperty = persistentClass.getProperty("price");
    assertEquals(2, priceProperty.getColumnSpan());
    assertEquals("price", priceProperty.getName());

    Iterator<?> colIter = priceProperty.getColumnIterator();
    column = (Column) colIter.next();
    assertEquals("value", column.getName());
    assertNull("SQL type should have been 'null' for 'value' column.", column.getSqlType());

    column = (Column) colIter.next();
    assertEquals("currency_code", column.getName());
    assertEquals("text", column.getSqlType());
  }
Пример #28
0
 /** initialize the validators, any non significant validators are not kept */
 @SuppressWarnings("unchecked")
 public synchronized void initialize(final Configuration cfg) {
   if (!isInitialized) {
     Iterator<PersistentClass> classes = (Iterator<PersistentClass>) cfg.getClassMappings();
     while (classes.hasNext()) {
       PersistentClass clazz = classes.next();
       final Class mappedClass = clazz.getMappedClass();
       ClassValidator validator = new ClassValidator(mappedClass);
       ValidatableElement element = new ValidatableElement(mappedClass, validator);
       addSubElement(clazz.getIdentifierProperty(), element);
       Iterator properties = clazz.getPropertyIterator();
       while (properties.hasNext()) {
         addSubElement((Property) properties.next(), element);
       }
       if (element.subElements.size() != 0 || element.validator.hasValidationRules()) {
         validators.put(mappedClass, element);
       }
     }
     isInitialized = true;
   }
 }
  /**
   * Generates the attribute representation of the identifier for a given entity mapping.
   *
   * @param mappedEntity The mapping definition of the entity.
   * @param generator The identifier value generator to use for this identifier.
   * @return The appropriate IdentifierProperty definition.
   */
  public static IdentifierProperty buildIdentifierAttribute(
      PersistentClass mappedEntity, IdentifierGenerator generator) {
    String mappedUnsavedValue = mappedEntity.getIdentifier().getNullValue();
    Type type = mappedEntity.getIdentifier().getType();
    Property property = mappedEntity.getIdentifierProperty();

    IdentifierValue unsavedValue =
        UnsavedValueFactory.getUnsavedIdentifierValue(
            mappedUnsavedValue, getGetter(property), type, getConstructor(mappedEntity));

    if (property == null) {
      // this is a virtual id property...
      return new IdentifierProperty(
          type,
          mappedEntity.hasEmbeddedIdentifier(),
          mappedEntity.hasIdentifierMapper(),
          unsavedValue,
          generator);
    } else {
      return new IdentifierProperty(
          property.getName(),
          property.getNodeName(),
          type,
          mappedEntity.hasEmbeddedIdentifier(),
          unsavedValue,
          generator);
    }
  }
  @SuppressWarnings({"unchecked"})
  private String searchMappedBy(PersistentClass referencedClass, Collection collectionValue) {
    Iterator<Property> assocClassProps = referencedClass.getPropertyIterator();
    while (assocClassProps.hasNext()) {
      Property property = assocClassProps.next();

      if (Tools.iteratorsContentEqual(
          property.getValue().getColumnIterator(), collectionValue.getKey().getColumnIterator())) {
        return property.getName();
      }
    }
    return null;
  }