List of usage examples for org.hibernate.metadata ClassMetadata getPropertyNames
String[] getPropertyNames();
From source file:bo.com.offercruz.dal.base.DAOGenericoHibernate.java
public boolean isEntidadEliminacionLogica() { ClassMetadata classMetadata = getSession().getSessionFactory().getClassMetadata(getPersistentClass()); String[] propertyNames = classMetadata.getPropertyNames(); for (String string : propertyNames) { if ("estado".equals(string)) { return true; }//from ww w.j av a 2 s. co m } return false; }
From source file:com.autobizlogic.abl.data.hibernate.HibPersistentBeanCopy.java
License:Open Source License
/** * Create from a state array.// w w w.j a va2 s .co m * @param The state (typically from a Hibernate event) * @param pk The primary key * @param persister The persister for the object */ @SuppressWarnings("unchecked") protected HibPersistentBeanCopy(Object[] state, Object entity, Serializable pk, EntityPersister persister, Session session) { if (entity instanceof Map) map = (Map<String, Object>) entity; else { bean = entity; beanMap = new BeanMap(entity); } this.pk = pk; this.metaEntity = MetaModelFactory.getHibernateMetaModel(persister.getFactory()) .getMetaEntity(persister.getEntityName()); ClassMetadata metadata = persister.getClassMetadata(); String[] propNames = metadata.getPropertyNames(); for (int i = 0; i < propNames.length; i++) { String propName = propNames[i]; if (metaEntity.getMetaProperty(propName).isCollection()) continue; MetaRole metaRole = metaEntity.getMetaRole(propName); if (metaRole == null) { // Not a relationship -- must be an attribute if (state[i] != null) values.put(propName, state[i]); } else if (!metaRole.isCollection()) { // In the case of old values, when we are handed the state, it contains the pk for associations, // and not (as you'd expect) the object itself. So we check whether the value is a real object, // and if it's not, we grab it from the object. if (state[i] == null || session.contains(state[i])) { values.put(propName, state[i]); } else { // We have a pk instead of a proxy -- ask Hibernate to create a proxy for it. String className = metadata.getPropertyType(propName).getReturnedClass().getName(); PersistenceContext persContext = HibernateSessionUtil.getPersistenceContextForSession(session); EntityPersister entityPersister = HibernateSessionUtil.getEntityPersister(session, className, bean); EntityKey entityKey = new EntityKey((Serializable) state[i], entityPersister, session.getEntityMode()); // Has a proxy already been created for this session? Object proxy = persContext.getProxy(entityKey); if (proxy == null) { // There is no proxy anywhere for this object, so ask Hibernate to create one for us proxy = entityPersister.createProxy((Serializable) state[i], (SessionImplementor) session); persContext.getBatchFetchQueue().addBatchLoadableEntityKey(entityKey); persContext.addProxy(entityKey, proxy); } values.put(propName, proxy); } } } }
From source file:com.autobizlogic.abl.logic.LogicSvcs.java
License:Open Source License
/** * //w w w .j a v a2 s . c o m * @param aSourceHibernateBean * @param aLogicRunner - just for context * @return 2nd instance of aSourceHibernateBean, with non-collection properties */ public static Object beanCopyOf(Object aSourceHibernateBean, LogicRunner aLogicRunner) { Object rtnTargetHibernateBean = null; LogicTransactionContext context = aLogicRunner.getContext(); BigDecimal defaultValue = null; //new BigDecimal("0.0"); // an experiment Converter bdc = new BigDecimalConverter(defaultValue); ConvertUtils.register(bdc, BigDecimal.class); Class<?> hibernateDomainBeanClass = HibernateUtil.getEntityClassForBean(aSourceHibernateBean); ClassMetadata entityMeta = context.getSession().getSessionFactory() .getClassMetadata(hibernateDomainBeanClass); Type propertyTypes[] = entityMeta.getPropertyTypes(); String propertyNames[] = entityMeta.getPropertyNames(); // hope names/types share index... String className = hibernateDomainBeanClass.getName(); try { rtnTargetHibernateBean = ClassLoaderManager.getInstance().getClassFromName(className).newInstance(); } catch (Exception e) { throw new LogicException("Unable to instantatiate new Bean like: " + aSourceHibernateBean, e); } BeanMap rtnBeanMap = new BeanMap(rtnTargetHibernateBean); BeanMap srcBeanMap = new BeanMap(aSourceHibernateBean); Object eachValue = null; for (int i = 0; i < propertyNames.length; i++) { String propertyName = propertyNames[i]; try { Type type = propertyTypes[i]; if (!type.isCollectionType() && !type.isEntityType()) { // NB - not moving collections! eachValue = srcBeanMap.get(propertyName); rtnBeanMap.put(propertyName, eachValue); } else { BeanUtils.setProperty(rtnTargetHibernateBean, propertyNames[i], null); // prevent ClassCastException: HashSet cannot be cast to PersistentCollection } } catch (Exception e) { throw new LogicException("Cannot set Property: " + propertyNames[i] + " = " + eachValue + ", on " + rtnTargetHibernateBean); } } // TODO - IMPORTANT - set the key field(s), presumably using Hibernate meta data return rtnTargetHibernateBean; }
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. c o 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.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;/*from w w w . j av a 2 s. com*/ 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.court.controller.HomeFXMLController.java
private Map<String, Number> getLoanReleasedData() { LocalDate now = LocalDate.now(); Map<String, Number> map = new HashMap<>(); Session s = HibernateUtil.getSessionFactory().openSession(); Criteria c = s.createCriteria(MemberLoan.class); ProjectionList pList = Projections.projectionList(); ClassMetadata lpMeta = s.getSessionFactory().getClassMetadata(MemberLoan.class); pList.add(Projections.property(lpMeta.getIdentifierPropertyName())); for (String prop : lpMeta.getPropertyNames()) { pList.add(Projections.property(prop), prop); }//from w w w .j av a 2 s . c o m c.add(Restrictions.eq("status", true)); c.add(Restrictions.between("grantedDate", FxUtilsHandler.getDateFrom(now.with(firstDayOfYear())), FxUtilsHandler.getDateFrom(now.with(lastDayOfYear())))); c.setProjection(pList .add(Projections.sqlGroupProjection("DATE_FORMAT(granted_date, '%Y-%m-01') AS groupPro", "groupPro", new String[] { "groupPro" }, new Type[] { StringType.INSTANCE })) .add(Projections.sqlProjection("SUM(loan_amount) AS lSum", new String[] { "lSum" }, new Type[] { DoubleType.INSTANCE }))); c.addOrder(Order.asc("grantedDate")); c.setResultTransformer(Transformers.aliasToBean(MemberLoan.class)); List<MemberLoan> list = (List<MemberLoan>) c.list(); for (MemberLoan ml : list) { map.put(ml.getGroupPro(), ml.getlSum()); } s.close(); return map; }
From source file:com.court.controller.HomeFXMLController.java
private Map<String, Number> getLoanCollectionData() { LocalDate now = LocalDate.now(); Map<String, Number> map = new HashMap<>(); Session s = HibernateUtil.getSessionFactory().openSession(); Criteria c = s.createCriteria(LoanPayment.class); ProjectionList pList = Projections.projectionList(); ClassMetadata lpMeta = s.getSessionFactory().getClassMetadata(LoanPayment.class); pList.add(Projections.property(lpMeta.getIdentifierPropertyName())); for (String prop : lpMeta.getPropertyNames()) { pList.add(Projections.property(prop), prop); }//from ww w . j av a 2 s . c om c.add(Restrictions.between("paymentDate", FxUtilsHandler.getDateFrom(now.with(firstDayOfYear())), FxUtilsHandler.getDateFrom(now.with(lastDayOfYear())))); c.setProjection(pList .add(Projections.sqlGroupProjection("DATE_FORMAT(payment_date, '%Y-%m-01') AS groupPro", "groupPro", new String[] { "groupPro" }, new Type[] { StringType.INSTANCE })) .add(Projections.sqlProjection("SUM(paid_amt) AS lSum", new String[] { "lSum" }, new Type[] { DoubleType.INSTANCE }))); c.addOrder(Order.asc("paymentDate")); c.setResultTransformer(Transformers.aliasToBean(LoanPayment.class)); List<LoanPayment> list = (List<LoanPayment>) c.list(); for (LoanPayment lp : list) { map.put(lp.getGroupPro(), lp.getlSum()); } s.close(); return map; }
From source file:com.javaetmoi.core.persistence.hibernate.LazyLoadingUtil.java
License:Apache License
@SuppressWarnings("unchecked") private static void deepInflateEntity(final Session currentSession, Object entity, Set<String> recursiveGuard) throws HibernateException { if (entity == null) { return;/* w w w .j av a 2 s .c o m*/ } Class<? extends Object> persistentClass = entity.getClass(); if (entity instanceof HibernateProxy) { persistentClass = ((HibernateProxy) entity).getHibernateLazyInitializer().getPersistentClass(); } ClassMetadata classMetadata = currentSession.getSessionFactory().getClassMetadata(persistentClass); if (classMetadata == null) { return; } Serializable identifier = classMetadata.getIdentifier(entity, (AbstractSessionImpl) currentSession); String key = persistentClass.getName() + "|" + identifier; if (recursiveGuard.contains(key)) { return; } recursiveGuard.add(key); if (!Hibernate.isInitialized(entity)) { Hibernate.initialize(entity); } for (int i = 0, n = classMetadata.getPropertyNames().length; i < n; i++) { String propertyName = classMetadata.getPropertyNames()[i]; Type propertyType = classMetadata.getPropertyType(propertyName); Object propertyValue = null; if (entity instanceof javassist.util.proxy.ProxyObject) { // For javassist proxy, the classMetadata.getPropertyValue(..) method return en // emppty collection. So we have to call the property's getter in order to call the // JavassistLazyInitializer.invoke(..) method that will initialize the collection by // loading it from the database. propertyValue = callCollectionGetter(entity, propertyName); } else { propertyValue = classMetadata.getPropertyValue(entity, propertyName, EntityMode.POJO); } deepInflateProperty(propertyValue, propertyType, currentSession, recursiveGuard); } }
From source file:com.klistret.cmdb.utility.hibernate.XPathCriteria.java
License:Open Source License
/** * Get Hibernate property type by looking for the property name in the class * metadata for general properties and the identifier property * //ww w. j av a2 s.c o m * @param cm * @param name * @return */ private org.hibernate.type.Type getPropertyType(ClassMetadata cm, String name) { for (String pn : cm.getPropertyNames()) if (pn.equals(name)) return cm.getPropertyType(name); if (cm.getIdentifierPropertyName() != null && cm.getIdentifierPropertyName().equals(name)) return cm.getIdentifierType(); return null; }
From source file:com.mg.framework.service.PersistentObjectHibernate.java
License:Open Source License
public AttributeMap getAllAttributes() { org.hibernate.metadata.ClassMetadata meta = getFactory() .getClassMetadata(ReflectionUtils.getEntityClass(this)); String[] props = meta.getPropertyNames(); Object[] values = meta.getPropertyValues(this, getEntityMode()); AttributeMap result = new com.mg.framework.support.LocalDataTransferObject(); for (int i = 0; i < props.length; i++) { if (values[i] == LazyPropertyInitializer.UNFETCHED_PROPERTY) { //http://issues.m-g.ru/bugzilla/show_bug.cgi?id=4664 //? ? ?? ? , ? lazy //?? get set ? values[i] = getAttribute(props[i]); }// ww w . j av a 2s . com result.put(props[i], values[i]); } //put identifier result.put(meta.getIdentifierPropertyName(), meta.getIdentifier(this, getEntityMode())); //put custom fields if (customFieldsStorage != null) result.putAll(customFieldsStorage.getValues()); return result; }