List of usage examples for org.hibernate.metadata ClassMetadata getPropertyValue
Object getPropertyValue(Object object, String propertyName) throws HibernateException;
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. jav a 2 s . c o m*/ // 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:org.cgiar.ccafs.marlo.data.HibernateAuditLogListener.java
License:Open Source License
/** * This code should be simplified!!!/*from w w w .ja v a 2 s. c om*/ * * @param entity * @return * @throws SecurityException * @throws NoSuchFieldException * @throws IllegalAccessException * @throws IllegalArgumentException */ public Set<HashMap<String, Object>> loadListOfRelations(IAuditLog entity, Session session) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { Set<HashMap<String, Object>> setRelations = new HashSet<>(); entity = (IAuditLog) session.get(entity.getClass(), entity.getId()); ClassMetadata classMetadata = session.getSessionFactory().getClassMetadata(entity.getClass()); String[] propertyNames = classMetadata.getPropertyNames(); for (String name : propertyNames) { Object propertyValue = classMetadata.getPropertyValue(entity, name); Type propertyType = classMetadata.getPropertyType(name); if (propertyValue != null && (propertyType instanceof OrderedSetType || propertyType instanceof SetType)) { /** Add instanceof check to ensure no classCast exceptions. **/ Set<?> checkElementCollectionTypes = (Set<?>) propertyValue; /** Java type erasure means we have to do it this way **/ if (checkElementCollectionTypes.size() == 0 || !(checkElementCollectionTypes.iterator().next() instanceof IAuditLog)) { /** We don't want to record entities that are not instances of IAuditLog such as SectionStatus **/ continue; } HashMap<String, Object> objects = new HashMap<>(); Set<IAuditLog> listRelation = new HashSet<>(); /** Our instanceof check in the if statement above ensures that we will only be dealing with IAuditLog **/ @SuppressWarnings(value = { "unchecked" }) Set<IAuditLog> entityRelation = (Set<IAuditLog>) propertyValue; String fieldSet = propertyType.getName() .replaceAll("java.util.Set\\(" + entity.getClass().getName() + ".", "") .replaceAll("\\)", ""); Field privateField = entity.getClass().getDeclaredField(fieldSet); privateField.setAccessible(true); Set<IAuditLog> set = (Set<IAuditLog>) privateField.get(entity); for (IAuditLog iAuditLog : set) { if (iAuditLog.isActive()) { listRelation.add(iAuditLog); } } objects.put(IAuditLog.ENTITY, listRelation); objects.put(IAuditLog.PRINCIPAL, "3"); objects.put(IAuditLog.RELATION_NAME, propertyType.getName() + ":" + entity.getId()); setRelations.add(objects); } } return setRelations; }
From source file:org.cgiar.ccafs.marlo.data.HibernateAuditLogListener.java
License:Open Source License
@Override public void onPostUpdate(PostUpdateEvent postUpdateEvent) { Object entity = postUpdateEvent.getEntity(); LOG.debug("begin onPostUpdatefor Entity : " + entity); AuditLogContext auditLogContext = AuditLogContextProvider.getAuditLogContext(); /**// w w w . j av a 2 s. c om * This is because our save(entity), update(entity) and delete(entity) methods on our DAOs should not * execute the listeners. There might be a better way to do this like conditionally activate the listeners. */ if (auditLogContext.getActionName() == null && CollectionUtils.isEmpty(auditLogContext.getRelationsNames())) { LOG.debug("No audit log context setup for update on entity: " + entity); return; } /** * We might save many entities on a single request, but we only want to do the audit logging on one. */ if (!entity.getClass().getCanonicalName().equals(auditLogContext.getEntityCanonicalName())) { LOG.debug("Entity : " + entity + " , is not the entity we want to audit log"); return; } HashMap<String, Object> updateRecord = new HashMap<>(); if (entity instanceof IAuditLog) { IAuditLog iAuditLog = (IAuditLog) entity; String name = iAuditLog.getClass().getName(); Class<?> className = null; try { className = Class.forName(name); } catch (ClassNotFoundException e) { } Object obj = postUpdateEvent.getSession().get(className, iAuditLog.getId()); ClassMetadata classMetadata = postUpdateEvent.getSession().getSessionFactory() .getClassMetadata(obj.getClass()); Type[] types = classMetadata.getPropertyTypes(); String[] propertyNamesRelation = classMetadata.getPropertyNames(); Phase phaseObject = null; boolean hasPhase = false; for (String nameAtrribute : propertyNamesRelation) { if (nameAtrribute.equals("phase")) { try { phaseObject = (Phase) classMetadata.getPropertyValue(entity, nameAtrribute); } catch (Exception e) { // The attribute is not a Phase Model Class phaseObject = null; } if (phaseObject != null) { phaseObject = (Phase) postUpdateEvent.getSession().get(Phase.class, phaseObject.getId()); if (phaseObject != null) { hasPhase = true; } } } } /* * if have phase and the phase is the current we are checking , we load the info */ if (hasPhase || entity instanceof Project || entity instanceof FundingSource || entity instanceof Deliverable || entity instanceof ProjectOutcome || entity instanceof CrpProgram || entity instanceof ProjectExpectedStudy || entity instanceof ProjectInnovation) { if (hasPhase && (entity instanceof Deliverable == false)) { if (AuditLogContextProvider.getAuditLogContext().getPhase().equals(phaseObject)) { updateRecord.put(IAuditLog.ENTITY, entity); updateRecord.put(IAuditLog.PRINCIPAL, new Long(1)); auditLogContext.getUpdates().add(updateRecord); auditLogContext.getUpdates().addAll(this.relations(postUpdateEvent.getState(), types, ((IAuditLog) entity).getId(), true, postUpdateEvent.getSession(), obj)); postUpdateEvent.getSession().getActionQueue() .registerProcess(new MARLOAuditBeforeTransactionCompletionProcess()); } } else { updateRecord.put(IAuditLog.ENTITY, entity); updateRecord.put(IAuditLog.PRINCIPAL, new Long(1)); auditLogContext.getUpdates().add(updateRecord); auditLogContext.getUpdates().addAll(this.relations(postUpdateEvent.getState(), types, ((IAuditLog) entity).getId(), true, postUpdateEvent.getSession(), entity)); postUpdateEvent.getSession().getActionQueue() .registerProcess(new MARLOAuditBeforeTransactionCompletionProcess()); } } // LOG.debug("COMPARE LOGS WITH STAGING BRANCH: " + auditLogContext.getUpdates().toString()); } }
From source file:org.cgiar.ccafs.marlo.data.HibernateAuditLogListener.java
License:Open Source License
public Set<HashMap<String, Object>> relations(Object[] state, Type[] types, Object id, boolean firstRelations, Session session, Object object) { Set<HashMap<String, Object>> relations = new HashSet<>(); int i = 0;// www .ja v a 2s .c om String parentId = ""; try { parentId = id.toString(); } catch (Exception e1) { e1.printStackTrace(); parentId = ""; } /** * We load and refresh the object to get the relations updated. * Christian Garcia */ for (Type type : types) { HashMap<String, Object> objects = new HashMap<>(); if (type instanceof OneToOneType) { IAuditLog audit = (IAuditLog) state[i]; if (audit != null) { String name = audit.getClass().getName(); Class<?> className; try { className = Class.forName(name); Object obj = session.get(className, audit.getId()); Set<IAuditLog> listRelation = new HashSet<>(); listRelation.add((IAuditLog) obj); IAuditLog auditlog = (IAuditLog) obj; auditlog = (IAuditLog) session.get(auditlog.getClass(), auditlog.getId()); // session.refresh(auditlog); Set<HashMap<String, Object>> loadList = this.loadListOfRelations(auditlog, session); for (HashMap<String, Object> hashMap : loadList) { HashSet<IAuditLog> relationAudit = (HashSet<IAuditLog>) hashMap.get(IAuditLog.ENTITY); for (IAuditLog iAuditLog2 : relationAudit) { Set<HashMap<String, Object>> loadListRelations = this .loadListOfRelations(iAuditLog2, session); relations.addAll(loadListRelations); } } relations.addAll(loadList); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } if (type instanceof OrderedSetType || type instanceof SetType) { if (AuditLogContextProvider.getAuditLogContext().getRelationsNames().contains(type.getName())) { Set<IAuditLog> listRelation = new HashSet<>(); try { String fieldSet = type.getName() .replaceAll("java.util.Set\\(" + object.getClass().getName() + ".", "") .replaceAll("\\)", ""); Field privateField = object.getClass().getDeclaredField(fieldSet); privateField.setAccessible(true); Set<Object> set = (Set<Object>) privateField.get(object); // Hibernate.initialize(set); if (set != null && !set.isEmpty()) { Object reObject = session.get( AuditLogContextProvider.getAuditLogContext().getEntityCanonicalName(), (Serializable) id); // session.refresh(reObject); ClassMetadata metadata = session.getSessionFactory() .getClassMetadata(reObject.getClass()); Object[] values = metadata.getPropertyValues(reObject); set = (Set<Object>) values[i]; for (Object iAuditLog : set) { if (iAuditLog instanceof IAuditLog) { IAuditLog audit = (IAuditLog) iAuditLog; if (audit.isActive()) { try { String name = audit.getClass().getName(); Class<?> className = Class.forName(name); /** * Ensure that lazy loaded collections are at least proxy instances (if not fetched). * If you are not getting all collections auditLogged it is because the Action classes are * persisting the detached entity and not copying across the managed collections (e.g. the ones * in our entities that are generally using Set). To overcome refactor the Action classes to copy * the List collections, which are full of detached entities, see OutcomeAction save method for an * example. * When issue #1124 is solved, this won't be a problem. */ /** * We load the object to get the id assigned * Christian Garcia */ Object obj = session.get(className, audit.getId()); if (obj == null) { /** * This is likely to be that the entity has just been hard deleted (MARLO has a mixture of * entities * where some are soft deleted and others are hard deleted). */ LOG.info("IAuditLog obj with className: " + className + ", and id: " + audit.getId() + " can not be found"); // Add the audit from the state object array listRelation.add(audit); continue; } else { ClassMetadata classMetadataObj = session.getSessionFactory() .getClassMetadata(obj.getClass()); String[] propertyNamesRelation = classMetadataObj .getPropertyNames(); Phase phaseObject = null; boolean hasPhase = false; for (String nameAtrribute : propertyNamesRelation) { if (nameAtrribute.equals("phase")) { phaseObject = (Phase) classMetadataObj.getPropertyValue(obj, nameAtrribute); if (phaseObject != null) { phaseObject = (Phase) session.get(Phase.class, phaseObject.getId()); if (phaseObject != null) { hasPhase = true; } } } } /* * if have phase and the phase is the current we are checking , we load the info */ if (hasPhase) { if (AuditLogContextProvider.getAuditLogContext().getPhase() .equals(phaseObject)) { listRelation.add((IAuditLog) obj); IAuditLog auditlog = (IAuditLog) obj; auditlog = (IAuditLog) session.get(auditlog.getClass(), auditlog.getId()); // session.refresh(auditlog); Set<HashMap<String, Object>> loadList = this .loadListOfRelations(auditlog, session); for (HashMap<String, Object> hashMap : loadList) { HashSet<IAuditLog> relationAudit = (HashSet<IAuditLog>) hashMap .get(IAuditLog.ENTITY); for (IAuditLog iAuditLog2 : relationAudit) { Set<HashMap<String, Object>> loadListRelations = this .loadListOfRelations(iAuditLog2, session); relations.addAll(loadListRelations); } } relations.addAll(loadList); } } else { /* * If doesn't have phase we alway load the info */ listRelation.add((IAuditLog) obj); IAuditLog auditlog = (IAuditLog) obj; auditlog = (IAuditLog) session.get(auditlog.getClass(), auditlog.getId()); // session.refresh(auditlog); Set<HashMap<String, Object>> loadList = this .loadListOfRelations(auditlog, session); for (HashMap<String, Object> hashMap : loadList) { HashSet<IAuditLog> relationAudit = (HashSet<IAuditLog>) hashMap .get(IAuditLog.ENTITY); for (IAuditLog iAuditLog2 : relationAudit) { Set<HashMap<String, Object>> loadListRelations = this .loadListOfRelations(iAuditLog2, session); relations.addAll(loadListRelations); } } relations.addAll(loadList); } } } catch (ClassNotFoundException e) { LOG.error(e.getLocalizedMessage()); } } } } if (!listRelation.isEmpty()) { objects.put(IAuditLog.ENTITY, listRelation); objects.put(IAuditLog.PRINCIPAL, "3"); objects.put(IAuditLog.RELATION_NAME, type.getName() + ":" + parentId); relations.add(objects); } } } catch (HibernateException e) { e.printStackTrace(); LOG.info("Can not load lazy relation " + e.getLocalizedMessage()); } catch (IllegalArgumentException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IllegalAccessException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (NoSuchFieldException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (SecurityException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } i++; } return relations; }
From source file:org.unitime.timetable.action.HibernateQueryTestAction.java
License:Open Source License
public void printLine(StringBuffer s, Object o, SessionImplementor session) { s.append(//from w w w . j ava 2 s. c om "<tr align='left' onmouseover=\"this.style.backgroundColor='rgb(223,231,242)';\" onmouseout=\"this.style.backgroundColor='transparent';\" >"); SessionFactory hibSessionFactory = new _RootDAO().getSession().getSessionFactory(); if (o == null) { line(s, null); } else if (o instanceof Object[]) { Object[] x = (Object[]) o; for (int i = 0; i < x.length; i++) { if (x[i] == null) { line(s, null); } else { ClassMetadata meta = hibSessionFactory.getClassMetadata(x[i].getClass()); if (meta == null) { line(s, x[i]); } else { line(s, meta.getIdentifier(x[i], session)); for (int j = 0; j < meta.getPropertyNames().length; j++) if (!skip(meta.getPropertyTypes()[j], meta.getPropertyLaziness()[j])) line(s, meta.getPropertyValue(x[i], meta.getPropertyNames()[j])); } } } } else { ClassMetadata meta = hibSessionFactory.getClassMetadata(o.getClass()); if (meta == null) { line(s, o); } else { line(s, meta.getIdentifier(o, session)); for (int i = 0; i < meta.getPropertyNames().length; i++) if (!skip(meta.getPropertyTypes()[i], meta.getPropertyLaziness()[i])) line(s, meta.getPropertyValue(o, meta.getPropertyNames()[i])); } } s.append("</tr>"); }
From source file:org.unitime.timetable.backup.SessionBackup.java
License:Open Source License
@Override public void backup(OutputStream out, Progress progress, Long sessionId) throws IOException { iOut = CodedOutputStream.newInstance(out); iProgress = progress;/*from www.jav a 2 s . co m*/ iSessionId = sessionId; iHibSession = new _RootDAO().createNewSession(); iHibSession.setCacheMode(CacheMode.IGNORE); iHibSessionFactory = iHibSession.getSessionFactory(); try { iProgress.setStatus("Exporting Session"); iProgress.setPhase("Loading Model", 3); TreeSet<ClassMetadata> allMeta = new TreeSet<ClassMetadata>(new Comparator<ClassMetadata>() { @Override public int compare(ClassMetadata m1, ClassMetadata m2) { return m1.getEntityName().compareTo(m2.getEntityName()); } }); allMeta.addAll(iHibSessionFactory.getAllClassMetadata().values()); iProgress.incProgress(); Queue<QueueItem> queue = new LinkedList<QueueItem>(); queue.add(new QueueItem(iHibSessionFactory.getClassMetadata(Session.class), null, "uniqueId", Relation.None)); Set<String> avoid = new HashSet<String>(); // avoid following relations avoid.add(TimetableManager.class.getName() + ".departments"); avoid.add(TimetableManager.class.getName() + ".solverGroups"); avoid.add(DistributionType.class.getName() + ".departments"); avoid.add(LastLikeCourseDemand.class.getName() + ".student"); avoid.add(Student.class.getName() + ".lastLikeCourseDemands"); Set<String> disallowedNotNullRelations = new HashSet<String>(); disallowedNotNullRelations.add(Assignment.class.getName() + ".datePattern"); disallowedNotNullRelations.add(Assignment.class.getName() + ".timePattern"); disallowedNotNullRelations.add(LastLikeCourseDemand.class.getName() + ".student"); disallowedNotNullRelations.add(OnlineSectioningLog.class.getName() + ".session"); Map<String, List<QueueItem>> data = new HashMap<String, List<QueueItem>>(); List<QueueItem> sessions = new ArrayList<QueueItem>(); sessions.add(queue.peek()); data.put(queue.peek().name(), sessions); QueueItem item = null; while ((item = queue.poll()) != null) { if (item.size() == 0) continue; for (ClassMetadata meta : allMeta) { if (meta.hasSubclasses()) continue; for (int i = 0; i < meta.getPropertyNames().length; i++) { String property = meta.getPropertyNames()[i]; if (disallowedNotNullRelations.contains(meta.getEntityName() + "." + property) || meta.getPropertyNullability()[i]) continue; Type type = meta.getPropertyTypes()[i]; if (type instanceof EntityType && type.getReturnedClass().equals(item.clazz())) { QueueItem qi = new QueueItem(meta, item, property, Relation.Parent); if (!data.containsKey(qi.name())) { List<QueueItem> items = new ArrayList<QueueItem>(); data.put(qi.name(), items); queue.add(qi); items.add(qi); if (qi.size() > 0) iProgress.info("Parent: " + qi); } } } } } iProgress.incProgress(); for (List<QueueItem> list : data.values()) queue.addAll(list); // The following part is needed to ensure that instructor distribution preferences are saved including their distribution types List<QueueItem> distributions = new ArrayList<QueueItem>(); for (QueueItem instructor : data.get(DepartmentalInstructor.class.getName())) { QueueItem qi = new QueueItem(iHibSessionFactory.getClassMetadata(DistributionPref.class), instructor, "owner", Relation.Parent); distributions.add(qi); queue.add(qi); if (qi.size() > 0) iProgress.info("Extra: " + qi); } data.put(DistributionPref.class.getName(), distributions); while ((item = queue.poll()) != null) { if (item.size() == 0) continue; for (int i = 0; i < item.meta().getPropertyNames().length; i++) { String property = item.meta().getPropertyNames()[i]; Type type = item.meta().getPropertyTypes()[i]; if (type instanceof EntityType) { if (avoid.contains(item.name() + "." + property)) continue; ClassMetadata meta = iHibSessionFactory.getClassMetadata(type.getReturnedClass()); if (item.contains(meta.getEntityName())) continue; QueueItem qi = new QueueItem(meta, item, property, Relation.One); List<QueueItem> items = data.get(qi.name()); if (items == null) { items = new ArrayList<QueueItem>(); data.put(qi.name(), items); } queue.add(qi); items.add(qi); if (qi.size() > 0) iProgress.info("One: " + qi); } if (type instanceof CollectionType) { if (avoid.contains(item.name() + "." + property)) continue; ClassMetadata meta = iHibSessionFactory.getClassMetadata(((CollectionType) type) .getElementType((SessionFactoryImplementor) iHibSessionFactory).getReturnedClass()); if (meta == null || item.contains(meta.getEntityName())) continue; QueueItem qi = new QueueItem(meta, item, property, Relation.Many); List<QueueItem> items = data.get(qi.name()); if (items == null) { items = new ArrayList<QueueItem>(); data.put(qi.name(), items); } queue.add(qi); items.add(qi); if (qi.size() > 0) iProgress.info("Many: " + qi); } } } iProgress.incProgress(); Map<String, Set<Serializable>> allExportedIds = new HashMap<String, Set<Serializable>>(); for (String name : new TreeSet<String>(data.keySet())) { List<QueueItem> list = data.get(name); Map<String, TableData.Table.Builder> tables = new HashMap<String, TableData.Table.Builder>(); for (QueueItem current : list) { if (current.size() == 0) continue; iProgress.info("Loading " + current); List<Object> objects = current.list(); if (objects == null || objects.isEmpty()) continue; iProgress.setPhase(current.abbv() + " [" + objects.size() + "]", objects.size()); objects: for (Object object : objects) { iProgress.incProgress(); // Get meta data (check for sub-classes) ClassMetadata meta = iHibSessionFactory.getClassMetadata(object.getClass()); if (meta == null) meta = current.meta(); if (meta.hasSubclasses()) { for (Iterator i = iHibSessionFactory.getAllClassMetadata().entrySet().iterator(); i .hasNext();) { Map.Entry entry = (Map.Entry) i.next(); ClassMetadata classMetadata = (ClassMetadata) entry.getValue(); if (classMetadata.getMappedClass().isInstance(object) && !classMetadata.hasSubclasses()) { meta = classMetadata; break; } } } // Get unique identifier Serializable id = meta.getIdentifier(object, (SessionImplementor) iHibSession); // Check if already exported Set<Serializable> exportedIds = allExportedIds.get(meta.getEntityName()); if (exportedIds == null) { exportedIds = new HashSet<Serializable>(); allExportedIds.put(meta.getEntityName(), exportedIds); } if (!exportedIds.add(id)) continue; // Check relation to an academic session (if exists) for (String property : meta.getPropertyNames()) { Type type = meta.getPropertyType(property); if (type instanceof EntityType && type.getReturnedClass().equals(Session.class)) { Session s = (Session) meta.getPropertyValue(object, property); if (s != null && !s.getUniqueId().equals(iSessionId)) { iProgress.warn(meta.getEntityName() .substring(meta.getEntityName().lastIndexOf('.') + 1) + "@" + id + " belongs to a different academic session (" + s + ")"); continue objects; // wrong session } } } // Get appropriate table TableData.Table.Builder table = tables.get(meta.getEntityName()); if (table == null) { table = TableData.Table.newBuilder(); tables.put(meta.getEntityName(), table); table.setName(meta.getEntityName()); } // Export object TableData.Record.Builder record = TableData.Record.newBuilder(); record.setId(id.toString()); for (String property : meta.getPropertyNames()) { Type type = meta.getPropertyType(property); Object value = meta.getPropertyValue(object, property); if (value == null) continue; TableData.Element.Builder element = TableData.Element.newBuilder(); element.setName(property); if (type instanceof PrimitiveType) { element.addValue(((PrimitiveType) type).toString(value)); } else if (type instanceof StringType) { element.addValue(((StringType) type).toString((String) value)); } else if (type instanceof BinaryType) { element.addValueBytes(ByteString.copyFrom((byte[]) value)); } else if (type instanceof TimestampType) { element.addValue(((TimestampType) type).toString((Date) value)); } else if (type instanceof DateType) { element.addValue(((DateType) type).toString((Date) value)); } else if (type instanceof EntityType) { List<Object> ids = current.relation(property, id, false); if (ids != null) for (Object i : ids) element.addValue(i.toString()); iHibSession.evict(value); } else if (type instanceof CustomType && value instanceof Document) { if (object instanceof CurriculumClassification && property.equals("students")) continue; StringWriter w = new StringWriter(); XMLWriter x = new XMLWriter(w, OutputFormat.createCompactFormat()); x.write((Document) value); x.flush(); x.close(); element.addValue(w.toString()); } else if (type instanceof CollectionType) { List<Object> ids = current.relation(property, id, false); if (ids != null) for (Object i : ids) element.addValue(i.toString()); } else if (type instanceof EmbeddedComponentType && property.equalsIgnoreCase("uniqueCourseNbr")) { continue; } else { iProgress.warn("Unknown data type: " + type + " (property " + meta.getEntityName() + "." + property + ", class " + value.getClass() + ")"); continue; } record.addElement(element.build()); } table.addRecord(record.build()); iHibSession.evict(object); } current.clearCache(); } for (TableData.Table.Builder table : tables.values()) { add(table.build()); } } /* // Skip ConstraintInfo if (!iData.containsKey(ConstraintInfo.class.getName())) iData.put(ConstraintInfo.class.getName(), new QueueItem(iHibSessionFactory.getClassMetadata(ConstraintInfo.class), null, null, Relation.Empty)); for (String name: items) export(iData.get(name)); while (true) { List<Object> objects = new ArrayList<Object>(); ClassMetadata meta = null; for (Entity e: iObjects) { if (e.exported()) continue; if (objects.isEmpty() || meta.getEntityName().equals(e.name())) { meta = e.meta(); objects.add(e.object()); e.notifyExported(); } } if (objects.isEmpty()) break; export(meta, objects, null); } */ iProgress.setStatus("All done."); } finally { iHibSession.close(); } }
From source file:org.unitime.timetable.export.hql.SavedHqlExportToCSV.java
License:Open Source License
private static void line(String[] ret, Object o, SessionImplementor session) { if (o == null) { ret[0] = ""; } else if (o instanceof Object[]) { int idx = 0; for (Object x : (Object[]) o) { if (x == null) { ret[idx++] = ""; } else { ClassMetadata meta = SavedHQLDAO.getInstance().getSession().getSessionFactory() .getClassMetadata(x.getClass()); if (meta == null) { ret[idx++] = toString(x); } else { if (meta.getIdentifierPropertyName() != null) ret[idx++] = toString(meta.getIdentifier(x, session)); for (int i = 0; i < meta.getPropertyNames().length; i++) { if (!skip(meta.getPropertyTypes()[i], meta.getPropertyLaziness()[i])) ret[idx++] = toString(meta.getPropertyValue(x, meta.getPropertyNames()[i])); }//from ww w .ja v a 2s .c o m } } } } else { ClassMetadata meta = SavedHQLDAO.getInstance().getSession().getSessionFactory() .getClassMetadata(o.getClass()); if (meta == null) { ret[0] = toString(o); } else { int idx = 0; if (meta.getIdentifierPropertyName() != null) ret[idx++] = toString(meta.getIdentifier(o, session)); for (int i = 0; i < meta.getPropertyNames().length; i++) { if (!skip(meta.getPropertyTypes()[i], meta.getPropertyLaziness()[i])) ret[idx++] = toString(meta.getPropertyValue(o, meta.getPropertyNames()[i])); } } } }
From source file:org.zanata.model.validator.UniqueValidator.java
License:Open Source License
private int countRows(Object value) { // we need to use entityManager.unwrap because injected session will // be a weld proxy and criteria.getExecutableCriteria method will try // to cast it to SessionImplementor (ClassCastException) Session session = entityManager.unwrap(Session.class); ClassMetadata metadata = session.getSessionFactory().getClassMetadata(value.getClass()); String idName = metadata.getIdentifierPropertyName(); // FIXME was EntityMode.POJO Serializable id = metadata.getIdentifier(value, null); DetachedCriteria criteria = DetachedCriteria.forClass(value.getClass()); for (String property : parameters.properties()) { // FIXME was EntityMode.POJO criteria.add(Restrictions.eq(property, metadata.getPropertyValue(value, property))); }//w w w . j a v a 2 s. c o m // Id property if (id != null) { criteria.add(Restrictions.ne(idName, id)); } criteria.setProjection(Projections.rowCount()); // change the flush mode temporarily to perform the query or else // incomplete entities will try to get flushed // After the query, go back to the original mode FlushMode flushMode = session.getFlushMode(); session.setFlushMode(FlushMode.MANUAL); List results = criteria.getExecutableCriteria(session).list(); Number count = (Number) results.iterator().next(); session.setFlushMode(flushMode); return count.intValue(); }