public static EntityIdentifierDefinition buildSimpleEncapsulatedIdentifierDefinition(final AbstractEntityPersister entityPersister) { return new EncapsulatedEntityIdentifierDefinition() { private final AttributeDefinitionAdapter attr = new AttributeDefinitionAdapter( entityPersister); @Override public AttributeDefinition getAttributeDefinition() { return attr; } @Override public boolean isEncapsulated() { return true; } @Override public EntityDefinition getEntityDefinition() { return entityPersister; } }; }
public static EntityIdentifierDefinition buildEncapsulatedCompositeIdentifierDefinition( final AbstractEntityPersister entityPersister) { return new EncapsulatedEntityIdentifierDefinition() { private final CompositionDefinitionAdapter compositionDefinition = new CompositionDefinitionAdapter( entityPersister ); @Override public AttributeDefinition getAttributeDefinition() { return compositionDefinition; } @Override public boolean isEncapsulated() { return true; } @Override public EntityDefinition getEntityDefinition() { return entityPersister; } }; }
@Transactional public void truncate() throws Exception { List<String> tableNames = new ArrayList<>(); Session session = entityManager.unwrap(Session.class); Map<String, ClassMetadata> hibernateMetadata = session.getSessionFactory().getAllClassMetadata(); for (ClassMetadata classMetadata : hibernateMetadata.values()) { AbstractEntityPersister aep = (AbstractEntityPersister) classMetadata; tableNames.add(aep.getTableName()); } entityManager.flush(); entityManager.createNativeQuery("SET REFERENTIAL_INTEGRITY FALSE").executeUpdate(); tableNames.forEach(tableName -> entityManager.createNativeQuery("TRUNCATE TABLE " + tableName).executeUpdate()); entityManager.createNativeQuery("SET REFERENTIAL_INTEGRITY TRUE").executeUpdate(); }
/** * REVISAR NIKOLAS */ @Override public String[] getColumns( String propertyName, Criteria subcriteria) throws HibernateException { // return getPropertyMapping( getEntityName( subcriteria, propertyName ) ) // .toColumns( // getSQLAlias( subcriteria, propertyName ), // getPropertyName( propertyName ) // ); String alias = getSQLAlias( subcriteria, propertyName ); String property = getPropertyName( propertyName ); String _root = AbstractEntityPersister.generateTableAlias( alias, 0 ); return new String[]{_root+"."+property}; }
private static void modifyConstraints(SessionFactoryImpl sessionFactoryImpl) { ClassMetadata classMetadata = sessionFactoryImpl.getClassMetadata(MCRCategoryImpl.class); AbstractEntityPersister aep = (AbstractEntityPersister) classMetadata; String qualifiedTableName = aep.getTableName(); try (Session session = sessionFactoryImpl.openSession()) { session.doWork(connection -> { String updateStmt = Stream.of("ClassLeftUnique", "ClassRightUnique") .flatMap(idx -> Stream.of("drop constraint if exists " + idx, MessageFormat.format( "add constraint {0} unique ({1}) deferrable initially deferred", idx, getUniqueColumns(MCRCategoryImpl.class, idx)))) .collect(Collectors.joining(", ", getAlterTableString(connection) + qualifiedTableName + " ", "")); try (Statement stmt = connection.createStatement()) { LogManager.getLogger().info("Fixing PostgreSQL Schema for {}:\n{}", qualifiedTableName, updateStmt); stmt.execute(updateStmt); } }); } }
private static void fixCompositeIdentifierInMetaModel(SessionFactory sessionFactory, Class clazz) { ClassMetadata classMetadata = sessionFactory.getClassMetadata(clazz); if (classMetadata instanceof AbstractEntityPersister) { AbstractEntityPersister persister = (AbstractEntityPersister) classMetadata; EntityMetamodel model = persister.getEntityMetamodel(); IdentifierProperty identifier = model.getIdentifierProperty(); try { Field field = IdentifierProperty.class.getDeclaredField("hasIdentifierMapper"); field.setAccessible(true); field.set(identifier, true); field.setAccessible(false); } catch (Exception ex) { throw new SystemException("Attempt to fix entity meta model with hack failed, reason: " + ex.getMessage(), ex); } } }
public HealthInfoDTO getAllDbMetaData() { List<TableInfoDTO> tables = new ArrayList<>(); try { Map<String, ClassMetadata> map = saudeDao.getAllDbMetaData(); map.forEach((k, v) -> tables.add(getTableInfo((AbstractEntityPersister) v))); Optional<IValidatorDatabase> validator = verificaDialetoUtilizado(); if (validator.isPresent()) { validator.get().checkAllInfoTable(tables); } } catch (Exception e) { getLogger().error(e.getMessage(), e); tables.clear(); } return new HealthInfoDTO(tables); }
private TableInfoDTO getTableInfo(AbstractEntityPersister persister) { TableInfoDTO tableInfoDTO = new TableInfoDTO(); String[] name = SqlUtil.replaceSingularSchemaName(persister.getTableName()).split("\\."); tableInfoDTO.setSchema(name[0]); tableInfoDTO.setTableName(name[1]); List<String> columns = new ArrayList<>(); String[] propertyNames = persister.getPropertyNames(); Arrays.asList(propertyNames).forEach(propertyName -> columns.add(persister.getPropertyColumnNames(propertyName)[0])); Arrays.asList(persister.getIdentifierColumnNames()).forEach(chave -> { if (!columns.contains(chave)) { columns.add(chave); } }); List<ColumnInfoDTO> columnsType = new ArrayList<>(); columns.forEach(col -> columnsType.add(new ColumnInfoDTO(col, true))); tableInfoDTO.setColumnsInfo(columnsType); return tableInfoDTO; }
/** * @see org.tools.hqlbuilder.common.HqlService#getProperties(java.lang.String) */ @Override public List<String> getProperties(String classname) { if (StringUtils.isBlank(classname)) { throw new IllegalArgumentException("classname"); } Map<String, ?> allClassMetadata = new MetadataResolver().getAllClassMetadata(sessionFactory); Object classMeta = allClassMetadata.get(classname); if (classMeta == null) { return null; } List<String> propertyNames = new ArrayList<>(Arrays.asList(AbstractEntityPersister.class.cast(classMeta).getPropertyNames())); propertyNames.remove("id"); propertyNames.remove("version"); return propertyNames; }
/** * Diese Methode lädt die Daten um eine Tabelle zu erzeugen. */ @Override public void onPreLoad(PreLoadEvent preLoadEvent) { //System.out.println("onPreLoad ausgelöst"); Serializable id = preLoadEvent.getId(); Object[] values = preLoadEvent.getState(); persister = (AbstractEntityPersister)preLoadEvent.getPersister(); //virtuelle Table aufbauen List<Row> rows = new ArrayList(); List<ColumnDescriptor> columnDescriptors = new ArrayList(); List<Column> columns = new ArrayList(); columnDescriptors.add(addIdentifierToColumns(columns, id)); columnDescriptors.addAll(addPropertiesToColumns(columns, values)); Row row = new Row(columns); rows.add(row); //Ergebnisse holen und in values verfrachten //System.out.println("Erzeuge virtuelle Tabelle: " + persister.getRootTableName()); Table table = new Table(persister.getRootTableName(), rows, columnDescriptors); TableReader reader = new TableReader(); table = reader.select(table); setValuesFromRow(table.getRows().get(0), values); }
/** * Return names of all properties that are defined in the mapped ancestors of the given * persister. Note that unmapped superclasses are deliberately ignored, because they shouldn't * affect the metadata. * * @param persister * @return set of property names. Empty if the persister doesn't have a superclass. */ HashSet<String> getSuperProperties(AbstractEntityPersister persister) { HashSet<String> set = new HashSet<String>(); String superClassName = persister.getMappedSuperclass(); if (superClassName == null) return set; ClassMetadata superMeta = _sessionFactory.getClassMetadata(superClassName); if (superMeta == null) return set; String[] superProps = superMeta.getPropertyNames(); set.addAll(Arrays.asList(superProps)); set.add(superMeta.getIdentifierPropertyName()); return set; }
/** * Get the column names for a given property as an array of unbracketed, * lowercase names. For a collection property, the column name is the inverse foreign key (i.e. * the column on the other table that points back to the persister's table) */ String[] getPropertyColumnNames(AbstractEntityPersister persister, String propertyName, Type propType) { String[] propColumnNames = null; if (propType.isCollectionType()) { propColumnNames = ((CollectionType) propType).getAssociatedJoinable((SessionFactoryImplementor) this._sessionFactory) .getKeyColumnNames(); } else { propColumnNames = persister.getPropertyColumnNames(propertyName); } if (propColumnNames == null || propColumnNames.length == 0) { // this happens when the property is part of the key propColumnNames = persister.getKeyColumnNames(); } // HACK for formula: when using formula propColumnNames[0] equals null if (propColumnNames[0] == null) { propColumnNames = new String[] { propertyName }; } return unBracket(propColumnNames); }
private String getGeneratorType(AbstractEntityPersister entityPersister) { String generatorType = null; IdentifierGenerator generator = entityPersister != null ? entityPersister.getIdentifierGenerator() : null; if (generator != null) { if (generator instanceof IdentityGenerator) generatorType = "Identity"; else if (generator instanceof Assigned) generatorType = "None"; else generatorType = "KeyGenerator"; } return generatorType; }
/** * Get composite ID sub-attribute definitions. * * @param entityPersister - the entity persister. * * @return composite ID sub-attribute definitions. */ public static Iterable<AttributeDefinition> getIdentifierSubAttributes(AbstractEntityPersister entityPersister) { return getSingularSubAttributes( entityPersister, entityPersister, (CompositeType) entityPersister.getIdentifierType(), entityPersister.getTableName(), entityPersister.getRootTableIdentifierColumnNames() ); }
@Override public String getAlias(String table) { if (table == null){ return rootAlias; } else{ return AbstractEntityPersister.generateTableAlias(rootAlias, AbstractEntityPersister.getTableId(table, tables)); } }
private void loadSystemTableList(SessionFactory sessionFactory) { Map<String, ClassMetadata> allClassMetadata = sessionFactory.getAllClassMetadata(); allClassMetadata.forEach((key, value) -> { AbstractEntityPersister abstractEntityPersister = (AbstractEntityPersister) value; SYSTEM_TABLE_LIST.add(abstractEntityPersister.getTableName()); }); }
/** * Find a foreign key matching the given property, by looking in the fkMap. * The property may be defined on the class or a superclass, so this function calls itself recursively. * @param propName Name of the property e.g. "Product" * @param meta Class metadata, for traversing the class hierarchy * @return The name of the foreign key, e.g. "ProductID" */ private String findForeignKey(String propName, ClassMetadata meta) { String relKey = meta.getEntityName() + '.' + propName; if (fkMap.containsKey(relKey)) { return fkMap.get(relKey); } else if (meta.isInherited() && meta instanceof AbstractEntityPersister) { String superEntityName = ((AbstractEntityPersister) meta).getMappedSuperclass(); ClassMetadata superMeta = sessionFactory.getClassMetadata(superEntityName); return findForeignKey(propName, superMeta); } else { throw new IllegalArgumentException("Foreign Key '" + relKey + "' could not be found."); } }
/** * Build the Breeze metadata as a nested HashMap. * The result can be converted to JSON and sent to the Breeze client. */ public Root buildMetadata() throws Exception { Root root = new Root(); for (ClassMetadata classMetadata: this.sessionFactory.getAllClassMetadata().values()) { if (classMetadata instanceof AbstractEntityPersister) { this.addClassToMetadata(root, (AbstractEntityPersister) classMetadata); } } return root; }
/** * Checks to see if a property is implemented in own class by checking to see if the parent * has the property also. * * @param abstractEntityPersister * @param propertyName * @return */ boolean hasOwnProperty(AbstractEntityPersister abstractEntityPersister, String propertyName) { for (Field field: abstractEntityPersister.getMappedClass().getDeclaredFields()) { if (field.getName().equals(propertyName)) { return true; } } return false; }
/** * Get the column names for a given property as a comma-delimited String of unbracketed, lowercase names. */ String getPropertyColumnNames(AbstractEntityPersister persister, String propertyName) { String propColumnNames[] = persister.getPropertyColumnNames(propertyName); if (propColumnNames.length == 0) { // this happens when the property is part of the key propColumnNames = persister.getKeyColumnNames(); } StringBuilder sb = new StringBuilder(); for (String s : propColumnNames) { if (sb.length() > 0) sb.append(','); sb.append(unBracket(s)); } return sb.toString().toLowerCase(); }
public static EntityIdentifierDefinition buildNonEncapsulatedCompositeIdentifierDefinition(final AbstractEntityPersister entityPersister) { return new NonEncapsulatedEntityIdentifierDefinition() { private final CompositionDefinitionAdapter compositionDefinition = new CompositionDefinitionAdapter( entityPersister ); @Override public Iterable<AttributeDefinition> getAttributes() { return compositionDefinition.getAttributes(); } @Override public Class getSeparateIdentifierMappingClass() { return entityPersister.getEntityMetamodel().getIdentifierProperty().getType().getReturnedClass(); } @Override public boolean isEncapsulated() { return false; } @Override public EntityDefinition getEntityDefinition() { return entityPersister; } @Override public Type getCompositeType() { return entityPersister.getEntityMetamodel().getIdentifierProperty().getType(); } @Override public AttributeSource getSource() { return compositionDefinition; } @Override public String getName() { // Not sure this is always kosher. See org.hibernate.tuple.entity.EntityMetamodel.hasNonIdentifierPropertyNamedId return "id"; } @Override public CompositeType getType() { return (CompositeType) getCompositeType(); } @Override public boolean isNullable() { return compositionDefinition.isNullable(); } }; }
AttributeDefinitionAdapter(AbstractEntityPersister entityPersister) { this.entityPersister = entityPersister; }
protected AbstractEntityPersister getEntityPersister() { return entityPersister; }
CompositionDefinitionAdapter(AbstractEntityPersister entityPersister) { super( entityPersister ); }
private static String getPropertyColumnName(Class entity, String property, SessionFactory sessionFactory) { ClassMetadata hibernateMetadata = sessionFactory.getClassMetadata(entity); AbstractEntityPersister persister = (AbstractEntityPersister) hibernateMetadata; String[] columnNames = persister.getPropertyColumnNames(property); return columnNames[0]; }
/** Renseigne l'attribut _metadataList. */ protected void initMetadata() { this.metadataList = new ArrayList<Metadata>(); Map<?, ?> allClassesMetadata = HibernateUtil.getSessionFactory().getAllClassMetadata(); for (Object key : allClassesMetadata.keySet()) { if (GeodatabaseHibernate.logger.isDebugEnabled()) { GeodatabaseHibernate.logger.debug("key = " + key); } ClassMetadata classMetadata = (ClassMetadata) allClassesMetadata.get(key); if (GeodatabaseHibernate.logger.isDebugEnabled()) { GeodatabaseHibernate.logger.debug("metadata = " + classMetadata); } String className = (classMetadata.getEntityName()); if (GeodatabaseHibernate.logger.isDebugEnabled()) { GeodatabaseHibernate.logger.debug("entity name = " + className); } Metadata metadataElt = new Metadata(); metadataElt.setClassName(className); String[] propertyNames = classMetadata.getPropertyNames(); if (GeodatabaseHibernate.logger.isDebugEnabled()) { for (int i = 0; i < propertyNames.length; i++) { GeodatabaseHibernate.logger.debug("property name " + i + " = " + propertyNames[i]); } } if (classMetadata instanceof AbstractEntityPersister) { metadataElt.setTableName(((AbstractEntityPersister) classMetadata).getRootTableName()); metadataElt.setIdFieldName(((AbstractEntityPersister) classMetadata).getIdentifierPropertyName()); metadataElt.setIdColumnName(((AbstractEntityPersister) classMetadata).getIdentifierColumnNames()[0]); // FIXME a revoir: aussi l'enveloppe, les srid, la dimension, et // d'autres... metadataElt.setGeomColumnName("geom"); if (GeodatabaseHibernate.logger.isDebugEnabled()) { GeodatabaseHibernate.logger.debug("table name = " + metadataElt.getTableName()); GeodatabaseHibernate.logger.debug("id field name = " + metadataElt.getIdFieldName()); GeodatabaseHibernate.logger.debug("id column name = " + metadataElt.getIdColumnName()); } } this.metadataList.add(metadataElt); } }
/** * Gets the properties matching the given columns. May be a component, but will not be an association. * @param persister * @param columnNames * @return */ static String[] getPropertyNamesForColumns(AbstractEntityPersister persister, String[] columnNames) { String[] propNames = persister.getPropertyNames(); Type[] propTypes = persister.getPropertyTypes(); for (int i = 0; i < propNames.length; i++) { String propName = propNames[i]; Type propType = propTypes[i]; if (propType.isAssociationType()) continue; String[] columnArray = persister.getPropertyColumnNames(i); if (namesEqual(columnArray, columnNames)) return new String[] { propName }; } // If we got here, maybe the property is the identifier String[] keyColumnArray = persister.getKeyColumnNames(); if (namesEqual(keyColumnArray, columnNames)) { if (persister.getIdentifierPropertyName() != null) { return new String[] { persister.getIdentifierPropertyName() }; } if (persister.getIdentifierType().isComponentType()) { ComponentType compType = (ComponentType) persister.getIdentifierType(); return compType.getPropertyNames(); } } if (columnNames.length > 1) { // go one-by-one through columnNames, trying to find a matching property. // TODO: maybe this should split columnNames into all possible combinations of ordered subsets, and try those ArrayList<String> propList = new ArrayList<String>(); String[] prop = new String[1]; for (int i = 0; i < columnNames.length; i++) { prop[0] = columnNames[i]; String[] names = getPropertyNamesForColumns(persister, prop); // recursive call if (names != null) propList.addAll(Arrays.asList(names)); } if (propList.size() > 0) return (String[]) propList.toArray(); } return null; }
/** * Add the metadata for an entity. * @param meta */ void addClass(ClassMetadata meta) { Class type = meta.getMappedClass(); String classKey = getEntityTypeName(type); HashMap<String, Object> cmap = new LinkedHashMap<String, Object>(); typeList.add(cmap); cmap.put("shortName", type.getSimpleName()); cmap.put("namespace", type.getPackage().getName()); if (meta instanceof AbstractEntityPersister) { AbstractEntityPersister entityPersister = (AbstractEntityPersister) meta; String superClassEntityName = entityPersister.getMappedSuperclass(); if (superClassEntityName != null) { Class superType = this.sessionFactory.getClassMetadata(superClassEntityName).getMappedClass(); String baseTypeName = this.getEntityTypeName(superType); cmap.put("baseTypeName", baseTypeName); } IdentifierGenerator generator = entityPersister != null ? entityPersister.getIdentifierGenerator() : null; if (generator != null) { String genType = null; if (generator instanceof IdentityGenerator) genType = "Identity"; else if (generator instanceof Assigned) genType = "None"; else genType = "KeyGenerator"; cmap.put("autoGeneratedKeyType", genType); // TODO find the real generator } } String resourceName = pluralize(type.getSimpleName()); // TODO find the real name cmap.put("defaultResourceName", resourceName); resourceMap.put(resourceName, classKey); ArrayList<HashMap<String, Object>> dataArrayList = new ArrayList<HashMap<String, Object>>(); cmap.put("dataProperties", dataArrayList); ArrayList<HashMap<String, Object>> navArrayList = new ArrayList<HashMap<String, Object>>(); cmap.put("navigationProperties", navArrayList); try { this.addClassProperties(meta, dataArrayList, navArrayList); } catch (Exception e) { e.printStackTrace(); } }