List of usage examples for org.hibernate SessionFactory getClassMetadata
@Deprecated ClassMetadata getClassMetadata(String entityName);
From source file:egov.data.hibernate.repository.support.HibernateEntityInformationSupport.java
License:Apache License
public static <T> HibernateEntityInformation<T, ?> getMetadata(Class<T> domainClass, SessionFactory sessionFactory) { Assert.notNull(domainClass);//from ww w .j av a2 s .c om Assert.notNull(sessionFactory); ClassMetadata metadata = sessionFactory.getClassMetadata(domainClass); if (Persistable.class.isAssignableFrom(domainClass)) { return new HibernatePersistableEntityInformation(domainClass, metadata); } else { return new HibernateMetamodelEntityInformation(domainClass, metadata); } }
From source file:gov.nih.nci.security.upt.util.HibernateHelper.java
License:BSD License
public static HashMap getAssociatedClasses(String className) throws CSException { System.out.println("className " + className); boolean isParentClass = false; HttpSession session = WebContextFactory.get().getHttpServletRequest().getSession(); if (session.isNew() || (session.getAttribute(DisplayConstants.LOGIN_OBJECT) == null)) { throw new CSException("Session Expired - Please Relogin!"); }//w w w.j a v a 2 s. co m if (className.contains(" - self")) { throw new CSException("No Associations allowed for direct security filter clause."); } SessionFactory sessionFactory = (SessionFactory) session .getAttribute(DisplayConstants.HIBERNATE_SESSIONFACTORY); HashMap map = new HashMap(); if (!(className.contains(" - "))) { isParentClass = true; } else { className = className.substring(0, className.indexOf(" - ")); } System.out.println("className2 " + className); ClassMetadata classMetadata = sessionFactory.getClassMetadata(className); String[] properties = classMetadata.getPropertyNames(); for (int i = 0; i < properties.length; i++) { Type type = classMetadata.getPropertyType(properties[i]); if (type instanceof AssociationType) { try { AssociationType associationType = (AssociationType) type; map.put(properties[i], associationType.getAssociatedEntityName((SessionFactoryImplementor) sessionFactory) + " - " + properties[i]); } catch (Exception e) { throw new CSException("Hibernate Error: " + e.getMessage()); } } } System.out.println("isParentClass " + isParentClass); if (isParentClass) { map.put(className, className + " - self"); } if (map.size() == 0) throw new CSException("No associated Classes Found!"); System.out.println("map " + map); return map; }
From source file:gov.nih.nci.security.upt.util.HibernateHelper.java
License:BSD License
public static HashMap getAssociatedAttributes(String className) throws CSException { className = className.substring(0, className.indexOf(" - ")); HttpSession session = WebContextFactory.get().getHttpServletRequest().getSession(); if (session.isNew() || (session.getAttribute(DisplayConstants.LOGIN_OBJECT) == null)) { throw new CSException("Session Expired - Please Relogin!"); }/*from w w w. j a v a2 s . co m*/ SessionFactory sessionFactory = (SessionFactory) session .getAttribute(DisplayConstants.HIBERNATE_SESSIONFACTORY); HashMap map = new HashMap(); ClassMetadata classMetadata = sessionFactory.getClassMetadata(className); List propertiesList = new ArrayList(); String[] properties1 = classMetadata.getPropertyNames(); for (int count = 0; count < properties1.length; count++) { propertiesList.add(new String(properties1[count])); } propertiesList.add(new String(classMetadata.getIdentifierPropertyName())); Iterator propertiesIterator = propertiesList.iterator(); while (propertiesIterator.hasNext()) { String property = (String) propertiesIterator.next(); Type type = classMetadata.getPropertyType(property); if (!(type instanceof AssociationType)) { map.put(property + "-_-" + (type.getReturnedClass()).getName(), property); } } if (map.size() == 0) throw new CSException("No associated Classes Found!"); return map; }
From source file:gov.nih.nci.security.upt.util.HibernateHelper.java
License:BSD License
private static String modifySQLForUser(FilterClause filterClause, String generatedSQL, Session session, String peiTableOrViewName) { String targetClassName = null; if (StringUtils.isBlank(filterClause.getTargetClassAlias())) targetClassName = filterClause.getTargetClassName().substring(0, filterClause.getTargetClassName().indexOf(" - ")); else/*from w ww .j a va 2 s . c om*/ targetClassName = filterClause.getTargetClassAlias(); String targetClassAttributeName = null; if (StringUtils.isBlank(filterClause.getTargetClassAttributeAlias())) targetClassAttributeName = filterClause.getTargetClassAttributeName(); else targetClassAttributeName = filterClause.getTargetClassAttributeAlias(); String CSM_QUERY = " select pe.attribute_value from " + "csm_protection_group pg, " + "csm_protection_element pe, " + "csm_pg_pe pgpe, " + "csm_user_group_role_pg ugrpg, " + "csm_user u, " + "csm_role_privilege rp, " + "csm_role r, " + "csm_privilege p " + "where ugrpg.role_id = r.role_id " + "and ugrpg.user_id = u.user_id and " + "ugrpg.protection_group_id = ANY " + "(select pg1.protection_group_id " + "from csm_protection_group pg1 " + "where pg1.protection_group_id = pg.protection_group_id " + "or pg1.protection_group_id = " + "(select pg2.parent_protection_group_id " + "from csm_protection_group pg2 " + "where pg2.protection_group_id = pg.protection_group_id)) " + "and pg.protection_group_id = pgpe.protection_group_id " + "and pgpe.protection_element_id = pe.protection_element_id " + "and r.role_id = rp.role_id " + "and rp.privilege_id = p.privilege_id " + "and pe.object_id= '" + targetClassName + "' " + "and pe.attribute='" + targetClassAttributeName + "' " + "and p.privilege_name='READ' " + "and u.login_name=:USER_NAME " + "and pe.application_id=:APPLICATION_ID"; String CSM_QUERY_2 = "select upei.attribute_value from " + peiTableOrViewName + " upei where " + "upei.login_name=:USER_NAME and upei.application_id =:APPLICATION_ID and upei.privilege_name='READ'"; StringBuffer result = new StringBuffer(); String query = generatedSQL.substring(generatedSQL.indexOf('-') + 1, generatedSQL.length()); query = query.trim(); query = query.substring(0, query.indexOf('?')); String delimiters = "+-*/(),. "; StringTokenizer st = new StringTokenizer(query, delimiters, true); while (st.hasMoreTokens()) { String w = st.nextToken(); if (w.equals("this_")) { result = result.append("table_name_csm_"); } else if (w.equals("y0_")) { result = result.append(""); } else if (w.equals("as")) { result = result.append(""); } else { result = result.append(w); } } SessionFactory sessionFactory = session.getSessionFactory(); ClassMetadata classMetadata = sessionFactory.getClassMetadata(filterClause.getClassName()); String columnName = null; if (classMetadata instanceof AbstractEntityPersister) { AbstractEntityPersister abstractEntityPersister = (AbstractEntityPersister) classMetadata; String Id = abstractEntityPersister.getIdentifierPropertyName(); String[] columns = abstractEntityPersister.getPropertyColumnNames(Id); columnName = columns[0]; } if (!StringUtils.isBlank(peiTableOrViewName)) { query = columnName + " in (" + result.toString() + CSM_QUERY_2 + "))"; } else { query = columnName + " in (" + result.toString() + CSM_QUERY + "))"; } return query.toString(); }
From source file:gov.nih.nci.security.upt.util.HibernateHelper.java
License:BSD License
private static String modifySQLForGroup(FilterClause filterClause, String generatedSQL, Session session, String peiTableOrViewName) { String targetClassName = null; if (StringUtils.isBlank(filterClause.getTargetClassAlias())) targetClassName = filterClause.getTargetClassName().substring(0, filterClause.getTargetClassName().indexOf(" - ")); else//from w w w.j a v a 2s . c om targetClassName = filterClause.getTargetClassAlias(); String targetClassAttributeName = null; if (StringUtils.isBlank(filterClause.getTargetClassAttributeAlias())) targetClassAttributeName = filterClause.getTargetClassAttributeName(); else targetClassAttributeName = filterClause.getTargetClassAttributeAlias(); String CSM_QUERY = "SELECT Distinct pe.attribute_value " + "FROM CSM_PROTECTION_GROUP pg, " + " CSM_PROTECTION_ELEMENT pe, " + " CSM_PG_PE pgpe," + " CSM_USER_GROUP_ROLE_PG ugrpg, " + " CSM_GROUP g, " + " CSM_ROLE_PRIVILEGE rp, " + " CSM_ROLE r, " + " CSM_PRIVILEGE p " + "WHERE ugrpg.role_id = r.role_id " + "AND ugrpg.group_id = g.group_id " + "AND ugrpg.protection_group_id = ANY " + "( select pg1.protection_group_id from csm_protection_group pg1 " + " where pg1.protection_group_id = pg.protection_group_id OR pg1.protection_group_id = " + " (select pg2.parent_protection_group_id from csm_protection_group pg2 where pg2.protection_group_id = pg.protection_group_id)" + " ) " + "AND pg.protection_group_id = pgpe.protection_group_id " + "AND pgpe.protection_element_id = pe.protection_element_id " + "AND r.role_id = rp.role_id " + "AND rp.privilege_id = p.privilege_id " + "AND pe.object_id= '" + targetClassName + "' " + "AND p.privilege_name='READ' " + "AND g.group_name IN (:GROUP_NAMES ) " + "AND pe.application_id=:APPLICATION_ID"; String CSM_QUERY_2 = "select upei.attribute_value from " + peiTableOrViewName + " upei where " + "upei.group_name IN (:GROUP_NAMES) and upei.application_id =:APPLICATION_ID and upei.privilege_name='READ'"; /*String CSM_QUERY = " select pe.attribute_value from " + "csm_protection_group pg, " + "csm_protection_element pe, " + "csm_pg_pe pgpe, " + "csm_user_group_role_pg ugrpg, " + "csm_user u, " + "csm_role_privilege rp, " + "csm_role r, " + "csm_privilege p " + "where ugrpg.role_id = r.role_id " + "and ugrpg.user_id = u.user_id and " + "ugrpg.protection_group_id = ANY " + "(select pg1.protection_group_id " + "from csm_protection_group pg1 " + "where pg1.protection_group_id = pg.protection_group_id " + "or pg1.protection_group_id = " + "(select pg2.parent_protection_group_id " + "from csm_protection_group pg2 " + "where pg2.protection_group_id = pg.protection_group_id)) " + "and pg.protection_group_id = pgpe.protection_group_id " + "and pgpe.protection_element_id = pe.protection_element_id " + "and r.role_id = rp.role_id " + "and rp.privilege_id = p.privilege_id " + "and pe.object_id= '" + targetClassName + "' " + "and pe.attribute='" + targetClassAttributeName + "' " + "and p.privilege_name='READ' " + "and u.login_name=:USER_NAME " + "and pe.application_id=:APPLICATION_ID" ; */ StringBuffer result = new StringBuffer(); String query = generatedSQL.substring(generatedSQL.indexOf('-') + 1, generatedSQL.length()); query = query.trim(); query = query.substring(0, query.indexOf('?')); String delimiters = "+-*/(),. "; StringTokenizer st = new StringTokenizer(query, delimiters, true); while (st.hasMoreTokens()) { String w = st.nextToken(); if (w.equals("this_")) { result = result.append("table_name_csm_"); } else if (w.equals("y0_")) { result = result.append(""); } else if (w.equals("as")) { result = result.append(""); } else { result = result.append(w); } } SessionFactory sessionFactory = session.getSessionFactory(); ClassMetadata classMetadata = sessionFactory.getClassMetadata(filterClause.getClassName()); String columnName = null; if (classMetadata instanceof AbstractEntityPersister) { AbstractEntityPersister abstractEntityPersister = (AbstractEntityPersister) classMetadata; String Id = abstractEntityPersister.getIdentifierPropertyName(); String[] columns = abstractEntityPersister.getPropertyColumnNames(Id); columnName = columns[0]; } if (!StringUtils.isBlank(peiTableOrViewName)) { query = columnName + " in (" + result.toString() + CSM_QUERY_2 + "))"; } else { query = columnName + " in (" + result.toString() + CSM_QUERY + "))"; } return query.toString(); }
From source file:it.eng.qbe.datasource.hibernate.HibernatePersistenceManager.java
License:Mozilla Public License
public void updateRecord(JSONObject aRecord, RegistryConfiguration registryConf) { SessionFactory sf = dataSource.getHibernateSessionFactory(); Configuration cfg = dataSource.getHibernateConfiguration(); Session aSession = null;/*from w ww . ja v a 2 s .co m*/ Transaction tx = null; try { aSession = sf.openSession(); tx = aSession.beginTransaction(); String entityName = registryConf.getEntity(); PersistentClass classMapping = cfg.getClassMapping(entityName); ClassMetadata classMetadata = sf.getClassMetadata(entityName); String keyName = classMetadata.getIdentifierPropertyName(); Object key = aRecord.get(keyName); Property propertyId = classMapping.getProperty(keyName); //casts the id to the appropriate java type Object keyConverted = this.convertValue(key, propertyId); Object obj = aSession.load(entityName, (Serializable) keyConverted); Iterator it = aRecord.keys(); while (it.hasNext()) { String aKey = (String) it.next(); if (keyName.equals(aKey)) { continue; } Column c = registryConf.getColumnConfiguration(aKey); if (c.getSubEntity() != null) { // case of foreign key Property property = classMapping.getProperty(c.getSubEntity()); Type propertyType = property.getType(); if (propertyType instanceof ManyToOneType) { ManyToOneType manyToOnePropertyType = (ManyToOneType) propertyType; String entityType = manyToOnePropertyType.getAssociatedEntityName(); Object referenced = getReferencedObject(aSession, entityType, c.getField(), aRecord.get(aKey)); Setter setter = property.getSetter(obj.getClass()); setter.getMethod().invoke(obj, referenced); } else { throw new SpagoBIRuntimeException( "Property " + c.getSubEntity() + " is not a many-to-one relation"); } } else { // case of property Property property = classMapping.getProperty(aKey); Setter setter = property.getSetter(obj.getClass()); Object valueObj = aRecord.get(aKey); if (valueObj != null && !valueObj.equals("")) { Object valueConverted = this.convertValue(valueObj, property); setter.getMethod().invoke(obj, valueConverted); } } } aSession.saveOrUpdate(obj); tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } throw new RuntimeException(e); } finally { if (aSession != null) { if (aSession.isOpen()) aSession.close(); } } }
From source file:lucee.runtime.orm.hibernate.HibernateCaster.java
License:Open Source License
private static Query populateQuery(PageContext pc, HibernateORMSession session, Component cfc, Query qry) throws PageException { Property[] properties = CommonUtil.getProperties(cfc, true, true, false, false); String dsn = ORMUtil.getDataSourceName(pc, cfc); ComponentScope scope = cfc.getComponentScope(); HibernateORMEngine engine = (HibernateORMEngine) session.getEngine(); // init//from w ww .j av a 2s . c om if (qry == null) { SessionFactory factory = session.getRawSessionFactory(dsn); ClassMetadata md = factory.getClassMetadata(getEntityName(cfc)); Array names = CommonUtil.createArray(); Array types = CommonUtil.createArray(); String name; //ColumnInfo ci; int t; Object obj; Struct sct; String fieldType; for (int i = 0; i < properties.length; i++) { obj = properties[i].getMetaData(); if (obj instanceof Struct) { sct = (Struct) obj; fieldType = CommonUtil.toString(sct.get(CommonUtil.FIELDTYPE, null), null); if ("one-to-many".equalsIgnoreCase(fieldType) || "many-to-many".equalsIgnoreCase(fieldType) || "many-to-one".equalsIgnoreCase(fieldType) || "one-to-one".equalsIgnoreCase(fieldType)) continue; } name = HibernateUtil.validateColumnName(md, properties[i].getName(), null); //if(columnsInfo!=null)ci=(ColumnInfo) columnsInfo.get(name,null); //else ci=null; names.append(name); if (name != null) { t = HibernateCaster.toSQLType(HibernateUtil.getPropertyType(md, name).getName(), NULL); if (t == NULL) types.append("object"); else types.append(SQLCaster.toStringType(t)); } else types.append("object"); } qry = CommonUtil.createQuery(names, types, 0, getEntityName(cfc)); } // check else if (engine.getMode() == ORMEngine.MODE_STRICT) { if (!qry.getName().equals(getEntityName(cfc))) throw ExceptionUtil.createException(session, null, "can only merge entities of the same kind to a query", null); } // populate Key[] names = QueryUtil.getColumnNames(qry); int row = qry.addRow(); for (int i = 0; i < names.length; i++) { qry.setAtEL(names[i], row, scope.get(names[i], null)); } return qry; }
From source file:lucee.runtime.orm.hibernate.tuplizer.accessors.CFCGetter.java
License:Open Source License
@Override public Object get(Object trg) throws HibernateException { try {/*from w ww . j a va2s . c o m*/ // MUST cache this, perhaps when building xml PageContext pc = CommonUtil.pc(); ORMSession session = ORMUtil.getSession(pc); Component cfc = CommonUtil.toComponent(trg); String dsn = ORMUtil.getDataSourceName(pc, cfc); String name = HibernateCaster.getEntityName(cfc); SessionFactory sf = (SessionFactory) session.getRawSessionFactory(dsn); ClassMetadata metaData = sf.getClassMetadata(name); Type type = HibernateUtil.getPropertyType(metaData, key.getString()); Object rtn = cfc.getComponentScope().get(key, null); return HibernateCaster.toSQL(type, rtn, null); } catch (PageException pe) { throw new HibernatePageException(pe); } }
From source file:net.firejack.platform.core.store.BaseStore.java
License:Apache License
private Criteria createCriteria(Session session, Integer offset, Integer limit, Object example, List<String> nullableAssociations) { try {/*from w ww .ja va 2 s . c o m*/ Class<?> exampleClass = example.getClass(); Criteria criteria = session.createCriteria(exampleClass); // Map<String, Criteria> subcriterias = new HashMap<String, Criteria>(); if (limit != null && limit > -1) { criteria.setMaxResults(limit); } if (offset != null && offset > -1) { criteria.setFirstResult(offset); } Example exampleQuery = createExample(example); criteria.add(exampleQuery); SessionFactory sessionFactory = getHibernateTemplate().getSessionFactory(); ClassMetadata meta = sessionFactory.getClassMetadata(exampleClass); String[] names = meta.getPropertyNames(); Type[] propertyTypes = meta.getPropertyTypes(); for (int i = 0; i < propertyTypes.length; i++) { if (propertyTypes[i].isAssociationType() && !propertyTypes[i].isCollectionType()) { String name = names[i]; Object value = PropertyUtils.getProperty(example, name); if (value != null) { Example subExample = createExample(value); Criteria subcriteria = criteria.createCriteria(name); // subcriterias.put(name, subcriteria); subcriteria.add(subExample); } else if (nullableAssociations.contains(name)) { criteria.add(Restrictions.isNull(name)); } } else if (propertyTypes[i].isCollectionType()) { String name = names[i]; Collection values = (Collection) PropertyUtils.getProperty(example, name); JoinTable joinTable = getMethodAnnotation(JoinTable.class, example, name); if (values != null && values.size() > 0 && joinTable != null) { Table table = getClassAnnotation(Table.class, example); Enumerated enumerated = getMethodAnnotation(Enumerated.class, example, name); Object obj = values.iterator().next(); if (obj.getClass().isEnum()) { String sqlWhere = "{alias}.id IN (SELECT DISTINCT id_" + table.name() + " FROM " + joinTable.name() + " WHERE element IN ("; List<String> ordinals = new ArrayList<String>(); for (Object v : values) { if (enumerated != null && EnumType.STRING.equals(enumerated.value())) { ordinals.add("'" + String.valueOf(((Enum) v).name()) + "'"); } else { ordinals.add(String.valueOf(((Enum) v).ordinal())); } } String whereValues = StringUtils.join(ordinals.toArray(), ","); sqlWhere = sqlWhere + whereValues + "))"; criteria.add(Restrictions.sqlRestriction(sqlWhere)); } } } } return criteria; } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } }
From source file:org.apereo.portal.events.aggr.PortalRawEventsAggregatorImpl.java
License:Apache License
private List<String> getCollectionRoles(final SessionFactory sessionFactory, final Class<?> entityClass) { List<String> collectionRoles = entityCollectionRoles.get(entityClass); if (collectionRoles != null) { return collectionRoles; }//w w w. ja v a2s . c o m final com.google.common.collect.ImmutableList.Builder<String> collectionRolesBuilder = ImmutableList .builder(); final ClassMetadata classMetadata = sessionFactory.getClassMetadata(entityClass); for (final Type type : classMetadata.getPropertyTypes()) { if (type.isCollectionType()) { collectionRolesBuilder.add(((CollectionType) type).getRole()); } } collectionRoles = collectionRolesBuilder.build(); entityCollectionRoles.put(entityClass, collectionRoles); return collectionRoles; }