List of usage examples for org.hibernate.metadata ClassMetadata getEntityName
String getEntityName();
From source file:ariba.ui.meta.jpa.HibernateContext.java
License:Apache License
protected <T> T getIfAlreadyLoaded(java.lang.Class<T> tClass, Object primaryKey) { SessionImpl session = (SessionImpl) getSession(); ClassMetadata classMeta = session.getSessionFactory().getClassMetadata(tClass); String entityName = classMeta.getEntityName(); EntityPersister persister = session.getFactory().getEntityPersister(entityName); EntityKey entityKey = new EntityKey((Serializable) primaryKey, persister, EntityMode.POJO); return (T) ((SessionImpl) getSession()).getPersistenceContext().getEntity(entityKey); // return find(tClass, primaryKey); // return (T)getSession().get(tClass, (Serializable)primaryKey); }
From source file:ch.algotrader.dao.GenericDaoImpl.java
License:Open Source License
@Override public Object getInitializedCollection(final String role, final long id) { return this.txTemplate.execute(txStatus -> { SessionFactoryImpl sessionFactoryImpl = (SessionFactoryImpl) this.sessionFactory; CollectionPersister persister = sessionFactoryImpl.getCollectionPersister(role); // load the owner entity ClassMetadata ownerMetadata = persister.getOwnerEntityPersister().getClassMetadata(); Session session = this.sessionFactory.getCurrentSession(); Object owner = session.get(ownerMetadata.getEntityName(), id); // owner does not exist anymore so no point in loading the collection if (owner == null) { return null; }//from w w w . j a v a 2 s .c om // get the collection by it's property name Object col = ownerMetadata.getPropertyValue(owner, persister.getNodeName()); // if it is a PersistentCollection make sure it is initialized if (col instanceof PersistentCollection) { PersistentCollection collection = (PersistentCollection) col; if (!collection.wasInitialized()) { collection.forceInitialization(); } } return col; }); }
From source file:com.autobizlogic.abl.engine.phase.AdjustAllParents.java
License:Open Source License
/** * For each parent object, see if any adjustment is required (sums, count, ...) * @see #execute(LogicRunner)//from w w w. j a va2 s . co m */ @Override public void execute() { if (_logSys.isDebugEnabled()) _logSys.debug("#checking parent adjustments for", childLogicRunner); List<MetaRole> rtnRolesProcessed = new ArrayList<MetaRole>(); BusinessLogicFactory businessLogicFactory = BusinessLogicFactoryManager.getBusinessLogicFactory(); if (childDomainObject != null) { Set<MetaRole> childrenRoles = childDomainObject.getMetaEntity().getRolesFromChildToParents(); for (MetaRole eachChildrenRoles : childrenRoles) { MetaRole roleToChild = eachChildrenRoles.getOtherMetaRole(); if (roleToChild == null) // Is this a one-way relationship? If so, nothing to do in the parent continue; rtnRolesProcessed.add(roleToChild); MetaEntity parentEntity = roleToChild.getMetaEntity(); Object parentObject = getChildLogicRunner().getCurrentDomainObject() .get(eachChildrenRoles.getRoleName()); // Make sure that the parent and the child point to each other // In the case of a delete, Hibernate will often remove the child object from // the parent collection by the time we get here, so we can't really check. if (parentObject != null && !childDomainObject.isMap() && childLogicRunner.getVerb() != Verb.DELETE) { Object children = ObjectUtil.getProperty(parentObject, roleToChild.getName()); boolean badRelationship = false; if (children == null) badRelationship = true; else if (children instanceof Collection) { Collection<?> theChildren = (Collection<?>) children; if (!theChildren.contains(childDomainObject.getEntity())) { theChildren.contains(childDomainObject.getEntity()); for (Object o : theChildren) { System.out.println("Object " + o + " == " + childDomainObject.getEntity() + " : " + o.equals(childDomainObject.getEntity())); } badRelationship = true; } } if (badRelationship) HibernateUtil.failInconsistentRelationship(parentObject, childDomainObject, roleToChild); } // In case there is some inheritance situation, get the actual parent object and // see what class it is. if (parentObject != null && !parentObject.getClass().equals(parentEntity.getEntityClass()) && !parentEntity.isMap()) { Class<?> parentCls = ProxyUtil.getNonProxyClass(parentObject); ClassMetadata parentMeta = getChildLogicRunner().getContext().getSession().getSessionFactory() .getClassMetadata(parentCls); String parentEntityName = parentMeta.getEntityName(); parentEntity = parentEntity.getMetaModel().getMetaEntity(parentEntityName); } LogicGroup parentLg = RuleManager.getInstance(parentEntity.getMetaModel()) .getLogicGroupForEntity(parentEntity); if (parentLg == null && parentEntity.isMap()) continue; if (parentObject != null && parentLg == null) { SessionFactory sessFact = getChildLogicRunner().getContext().getSession().getSessionFactory(); Class<?> parentCls = ProxyUtil.getNonProxyClass(parentObject); while (parentLg == null) { parentCls = parentCls.getSuperclass(); if (parentCls.getName().equals("java.lang.Object")) break; ClassMetadata classMeta = sessFact.getClassMetadata(parentCls); if (classMeta == null) break; String parentEntityName = classMeta.getEntityName(); parentEntity = parentEntity.getMetaModel().getMetaEntity(parentEntityName); parentLg = RuleManager.getInstance(parentEntity.getMetaModel()) .getLogicGroupForEntity(parentEntity); } } if (parentLg == null) continue; Set<AbstractAggregateRule> aggregates = parentLg.findAggregatesForRole(roleToChild); adjustedParentDomainObject = null; // set in eachAggregate.adjustedParentDomainObject if appropriate adjustedOldParentDomainObject = null; adjustedPriorParentDomainObject = null; adjustedPriorOldParentDomainObject = null; for (AbstractAggregateRule eachAggregate : aggregates) { eachAggregate.adjustedParentDomainObject(this); // do adjusts into parent (on 1st, read and return parent handle) } if (adjustedParentDomainObject != null) { // save parent, which runs its rules (fwd chain) if (_logger.isDebugEnabled()) _logger.debug("Adjusting parent " + adjustedParentDomainObject.toShortString() + " from", childLogicRunner); LogicRunner parentLogicRunner = businessLogicFactory.getLogicRunner( childLogicRunner.getContext(), adjustedParentDomainObject, adjustedOldParentDomainObject, Verb.UPDATE, LogicSource.ADJUSTED, childLogicRunner, roleToChild); if (parentLogicRunner != null) parentLogicRunner.update(); } if (adjustedPriorParentDomainObject != null) { // save PRIOR parent, which runs its rules (fwd chain) FIXME REPARENT if (_logger.isDebugEnabled()) _logger.debug("Adjusting PRIOR Parent " + adjustedPriorParentDomainObject.toShortString() + " from", childLogicRunner); LogicRunner oldParentLogicRunner = businessLogicFactory.getLogicRunner( childLogicRunner.getContext(), adjustedPriorParentDomainObject, adjustedPriorOldParentDomainObject, Verb.UPDATE, LogicSource.ADJUSTED, childLogicRunner, roleToChild); if (oldParentLogicRunner != null) oldParentLogicRunner.update(); // See above } // adjustedOldParentDomeainObject != null } // eachChildrenRoles } // childDomainObject != null childLogicRunner.setAdjustedRolesDB(rtnRolesProcessed); }
From source file:com.autobizlogic.abl.metadata.hibernate.HibMetaEntity.java
License:Open Source License
/** * Read all the properties from Hibernate metadata *///from w w w .ja va 2 s .co m private void loadAllProperties() { if (allPropsRetrieved) return; synchronized (this) { if (!allPropsRetrieved) { metaAttributes = new HashMap<String, MetaAttribute>(); metaRoles = new HashMap<String, MetaRole>(); ClassMetadata meta = persister.getClassMetadata(); String[] propNames = meta.getPropertyNames(); for (String propName : propNames) { Type type; try { type = persister.getClassMetadata().getPropertyType(propName); } catch (QueryException ex) { throw new RuntimeException("Unable to determine type for property " + propName + " of entity " + persister.getEntityName()); } if (type.isComponentType()) { // Do nothing } else if (type.isCollectionType() || type.isEntityType() || type.isAssociationType()) { boolean isParentToChild = type.isCollectionType(); MetaRole mr = new HibMetaRole(this, propName, isParentToChild); metaRoles.put(propName, mr); } else { MetaAttribute ma = new HibMetaAttribute(propName, type.getReturnedClass(), false); metaAttributes.put(propName, ma); } } // Often the primary attribute(s) is not returned by ClassMetadata.getPropertyNames // So we add it by hand here String pkName = meta.getIdentifierPropertyName(); if (pkName == null) { // Can happen for composite keys Type pkType = meta.getIdentifierType(); if (pkType.isComponentType()) { ComponentType ctype = (ComponentType) pkType; String[] pnames = ctype.getPropertyNames(); for (String pname : pnames) { MetaAttribute ma = new HibMetaAttribute(pname, meta.getPropertyType(pname).getReturnedClass(), false); metaAttributes.put(pname, ma); } } else throw new RuntimeException( "Unexpected: anonymous PK is not composite - class " + meta.getEntityName()); } else if (!metaAttributes.containsKey(pkName)) { MetaAttribute ma = new HibMetaAttribute(pkName, meta.getIdentifierType().getReturnedClass(), false); metaAttributes.put(pkName, ma); } allPropsRetrieved = true; } } }
From source file:com.autobizlogic.abl.metadata.hibernate.HibMetaRole.java
License:Open Source License
/** * Get the inverse of a one-to-many role * @param entityName The entity owning the role * @param rName The role name//from ww w . j a v a 2 s. co m * @return Null if no inverse was found, otherwise [entity name, role name] of the inverse role */ private String[] getInverseOfCollectionRole(String entityName, String rName) { String[] result = new String[2]; SessionFactory sessFact = ((HibMetaModel) getMetaEntity().getMetaModel()).getSessionFactory(); AbstractCollectionPersister parentMeta = (AbstractCollectionPersister) sessFact .getCollectionMetadata(entityName + "." + rName); if (parentMeta == null) { // Could be inherited -- search through superclasses while (parentMeta == null) { Class<?> cls = null; if (getMetaEntity().getEntityType() == MetaEntity.EntityType.POJO) cls = sessFact.getClassMetadata(entityName).getMappedClass(EntityMode.POJO); else cls = sessFact.getClassMetadata(entityName).getMappedClass(EntityMode.MAP); Class<?> superCls = cls.getSuperclass(); if (superCls.getName().equals("java.lang.Object")) throw new RuntimeException( "Unable to retrieve Hibernate information for collection " + entityName + "." + rName); ClassMetadata clsMeta = sessFact.getClassMetadata(superCls); if (clsMeta == null) throw new RuntimeException("Unable to retrieve Hibernate information for collection " + entityName + "." + rName + ", even from superclass(es)"); entityName = clsMeta.getEntityName(); parentMeta = (AbstractCollectionPersister) sessFact.getCollectionMetadata(entityName + "." + rName); } } String[] colNames = parentMeta.getKeyColumnNames(); String childName = parentMeta.getElementType().getName(); AbstractEntityPersister childMeta = (AbstractEntityPersister) sessFact.getClassMetadata(childName); String[] propNames = childMeta.getPropertyNames(); for (int i = 0; i < propNames.length; i++) { Type type = childMeta.getPropertyType(propNames[i]); if (!type.isEntityType()) continue; EntityType entType = (EntityType) type; if (!entType.getAssociatedEntityName().equals(entityName)) continue; String[] cnames = childMeta.getPropertyColumnNames(i); if (cnames.length != colNames.length) continue; boolean columnMatch = true; for (int j = 0; j < cnames.length; j++) { if (!cnames[j].equals(colNames[j])) { columnMatch = false; break; } } if (columnMatch) { result[0] = childName; result[1] = propNames[i]; return result; } } return null; }
From source file:com.autobizlogic.abl.mgmt.ClassMetadataService.java
License:Open Source License
public static Map<String, Object> getMetadataForClass(Map<String, String> args) { String sessionFactoryId = args.get("sessionFactoryId"); String name = args.get("className"); HashMap<String, Object> result = new HashMap<String, Object>(); SessionFactory factory = HibernateConfiguration.getSessionFactoryById(sessionFactoryId); if (factory == null) return null; ClassMetadata meta = factory.getClassMetadata(name); if (meta == null) return null; result.put("sessionFactoryId", sessionFactoryId); result.put("className", meta.getEntityName()); result.put("identifierPropertyName", meta.getIdentifierPropertyName()); Class<?> cls = meta.getMappedClass(EntityMode.POJO); Class<?> supercls = cls.getSuperclass(); while (ProxyFactory.isProxyClass(supercls)) supercls = supercls.getSuperclass(); result.put("superclassName", supercls.getName()); Map<String, String> properties = new HashMap<String, String>(); Map<String, Object> collections = new HashMap<String, Object>(); Map<String, String> associations = new HashMap<String, String>(); String[] propNames = meta.getPropertyNames(); Type[] propTypes = meta.getPropertyTypes(); int i = 0;// ww w . j av a 2s . co m for (String propName : propNames) { if (propTypes[i].isCollectionType()) { CollectionType collType = (CollectionType) propTypes[i]; Type elementType = collType.getElementType((SessionFactoryImplementor) factory); HashMap<String, String> collEntry = new HashMap<String, String>(); collEntry.put("collectionType", collType.getReturnedClass().getName()); collEntry.put("elementType", elementType.getName()); collections.put(propName, collEntry); } else if (propTypes[i].isAssociationType()) { AssociationType assType = (AssociationType) propTypes[i]; String assName = assType.getAssociatedEntityName((SessionFactoryImplementor) factory); associations.put(propName, assName); } else { properties.put(propName, propTypes[i].getName()); } i++; } result.put("properties", properties); result.put("associations", associations); result.put("collections", collections); MetaModel metaModel = MetaModelFactory.getHibernateMetaModel(factory); LogicGroup logicGroup = RuleManager.getInstance(metaModel).getLogicGroupForClassName(name); if (logicGroup != null) { // Operations are actually actions and constraints List<Map<String, Object>> operations = new Vector<Map<String, Object>>(); result.put("operations", operations); Set<ActionRule> actions = logicGroup.getActions(); if (actions != null && actions.size() > 0) { for (ActionRule a : actions) { Map<String, Object> op = new HashMap<String, Object>(); op.put("name", a.getLogicMethodName()); op.put("type", "action"); operations.add(op); } } Set<EarlyActionRule> eactions = logicGroup.getEarlyActions(); if (eactions != null && eactions.size() > 0) { for (EarlyActionRule a : eactions) { Map<String, Object> op = new HashMap<String, Object>(); op.put("name", a.getLogicMethodName()); op.put("type", "early action"); operations.add(op); } } Set<CommitActionRule> cactions = logicGroup.getCommitActions(); if (cactions != null && cactions.size() > 0) { for (CommitActionRule a : cactions) { Map<String, Object> op = new HashMap<String, Object>(); op.put("name", a.getLogicMethodName()); op.put("type", "commit action"); operations.add(op); } } Set<ConstraintRule> constraints = logicGroup.getConstraints(); if (constraints != null && constraints.size() > 0) { for (ConstraintRule constraint : constraints) { Map<String, Object> op = new HashMap<String, Object>(); op.put("name", constraint.getLogicMethodName()); op.put("type", "constraint"); operations.add(op); } } Set<CommitConstraintRule> cconstraints = logicGroup.getCommitConstraints(); if (cconstraints != null && cconstraints.size() > 0) { for (ConstraintRule cconstraint : cconstraints) { Map<String, Object> op = new HashMap<String, Object>(); op.put("name", cconstraint.getLogicMethodName()); op.put("type", "commit constraint"); operations.add(op); } } // Derivations are derived attributes Map<String, Object> derivations = new HashMap<String, Object>(); result.put("derivations", derivations); Set<AbstractAggregateRule> aggregates = logicGroup.getAggregates(); if (aggregates != null && aggregates.size() > 0) { for (AbstractAggregateRule aggregate : aggregates) { Map<String, Object> agg = new HashMap<String, Object>(); if (aggregate instanceof CountRule) agg.put("type", "count"); else if (aggregate instanceof SumRule) agg.put("type", "sum"); else agg.put("type", "unknown"); agg.put("methodName", aggregate.getLogicMethodName()); derivations.put(aggregate.getBeanAttributeName(), agg); } } List<FormulaRule> formulas = logicGroup.getFormulas(); if (formulas != null && formulas.size() > 0) { for (FormulaRule formula : formulas) { Map<String, Object> form = new HashMap<String, Object>(); form.put("type", "formula"); form.put("methodName", formula.getLogicMethodName()); derivations.put(formula.getBeanAttributeName(), form); } } Set<ParentCopyRule> pcRules = logicGroup.getParentCopies(); if (pcRules != null && pcRules.size() > 0) { for (ParentCopyRule pcRule : pcRules) { Map<String, Object> parentCopy = new HashMap<String, Object>(); parentCopy.put("type", "parent copy"); parentCopy.put("methodName", pcRule.getLogicMethodName()); derivations.put(pcRule.getChildAttributeName(), parentCopy); } } } HashMap<String, Object> finalResult = new HashMap<String, Object>(); finalResult.put("data", result); return finalResult; }
From source file:com.bloatit.data.DaoMember.java
License:Open Source License
/** * Base method to all the get something created by the user. * * @param asMemberOnly the result must contains only result that are not * done as name of a team./*w ww . ja v a 2 s . c om*/ */ private <T extends DaoUserContent> PageIterable<T> getUserContent(final Class<T> theClass, final boolean asMemberOnly) { final ClassMetadata meta = SessionManager.getSessionFactory().getClassMetadata(theClass); final Query query = SessionManager.createQuery("from " + meta.getEntityName() + " as x where x.member = :author" + (asMemberOnly ? " AND x.asTeam = null" : "")); final Query size = SessionManager.createQuery("SELECT count(*) from " + meta.getEntityName() + " as x where x.member = :author" + (asMemberOnly ? " AND x.asTeam = null" : "")); final QueryCollection<T> q = new QueryCollection<T>(query, size); q.setEntity("author", this); return q; }
From source file:com.bloatit.data.queries.DBRequests.java
License:Open Source License
public static <T extends DaoIdentifiable> PageIterable<T> getAll(final Class<T> persistent) { final ClassMetadata meta = SessionManager.getSessionFactory().getClassMetadata(persistent); final Query query = SessionManager.createQuery("FROM " + meta.getEntityName() + " ORDER BY id DESC"); final Query size = SessionManager.createQuery("SELECT count(*) FROM " + meta.getEntityName()); return new QueryCollection<T>(query, size); }
From source file:com.bloatit.data.queries.DBRequests.java
License:Open Source License
public static <T extends DaoUserContent> PageIterable<T> getAllUserContentOrderByDate( final Class<T> persistent) { final ClassMetadata meta = SessionManager.getSessionFactory().getClassMetadata(persistent); return new QueryCollection<T>( SessionManager.createQuery("from " + meta.getEntityName() + " order by creationDate DESC"), SessionManager.createQuery("select count(*) from " + meta.getEntityName())); }
From source file:com.bloatit.data.queries.DBRequests.java
License:Open Source License
public static <T> Long count(final Class<T> persistent) { final ClassMetadata meta = SessionManager.getSessionFactory().getClassMetadata(persistent); return ((Long) SessionManager.getSessionFactory().getCurrentSession() .createQuery("select count(*) from " + meta.getEntityName()).uniqueResult()); }