List of usage examples for org.hibernate EntityMode POJO
EntityMode POJO
To view the source code for org.hibernate EntityMode POJO.
Click Source Link
From source file:org.openmrs.module.sync.api.db.hibernate.HibernateSyncInterceptor.java
License:Open Source License
/** * Processes changes to hibernate collections. At the moment, only persistent sets are * supported./*from w w w .j a v a 2s.co m*/ * <p> * Remarks: Note that simple lists and maps of primitive types are supported also by default via * normalizers and do not require explicit handling as shown here for sets of any reference * types. * <p> * * @param collection Instance of Hibernate AbstractPersistentCollection to process. * @param key key of owner for the collection. * @param action hibernate 'action' being performed: update, recreate. note, deletes are handled * via re-create */ protected void processHibernateCollection(AbstractPersistentCollection collection, Serializable key, String action) { if (!(collection instanceof PersistentSet || collection instanceof PersistentMap || collection instanceof PersistentList)) { log.debug("Unsupported collection type, collection type was:" + collection.getClass().getName()); return; } OpenmrsObject owner = null; String originalRecordUuid = null; LinkedHashMap<String, OpenmrsObject> entriesHolder = null; // we only process recreate and update if (!"update".equals(action) && !"recreate".equals(action)) { log.error("Unexpected 'action' supplied, valid values: recreate, update. value provided: " + action); throw new CallbackException("Unexpected 'action' supplied while processing a persistent set."); } // retrieve owner and original uuid if there is one if (collection.getOwner() instanceof OpenmrsObject) { owner = (OpenmrsObject) collection.getOwner(); if (!this.shouldSynchronize(owner)) { if (log.isDebugEnabled()) log.debug("Determined entity not to be journaled, exiting onDelete."); return; } originalRecordUuid = getSyncRecord().getOriginalUuid(); } else { log.debug("Cannot process collection where owner is not OpenmrsObject."); return; } /* * determine if this set needs to be processed. Process if: 1. it is * recreate or 2. is dirty && current state does not equal stored * snapshot */ boolean process = false; if ("recreate".equals(action)) { process = true; } else { if (collection.isDirty()) { org.hibernate.persister.collection.CollectionPersister persister = ((org.hibernate.engine.SessionFactoryImplementor) getSessionFactory()) .getCollectionPersister(collection.getRole()); Object ss = null; try { // code around hibernate bug: // http://opensource.atlassian.com/projects/hibernate/browse/HHH-2937 ss = collection.getSnapshot(persister); } catch (NullPointerException ex) { } if (ss == null) { log.debug("snapshot is null"); if (collection.empty()) process = false; else process = true; } else if (!collection.equalsSnapshot(persister)) { process = true; } ; } if (!process) { log.debug("set processing, no update needed: not dirty or current state and snapshots are same"); } } if (!process) return; // pull out the property name on owner that corresponds to the collection ClassMetadata data = getSessionFactory().getClassMetadata(owner.getClass()); String[] propNames = data.getPropertyNames(); // this is the name of the property on owner object that contains the set String ownerPropertyName = null; for (String propName : propNames) { Object propertyVal = data.getPropertyValue(owner, propName, org.hibernate.EntityMode.POJO); // note: test both with equals() and == because // PersistentSet.equals() // actually does not handle equality of two persistent sets well if (collection == propertyVal || collection.equals(propertyVal)) { ownerPropertyName = propName; break; } } if (ownerPropertyName == null) { log.error( "Could not find the property on owner object that corresponds to the collection being processed."); log.error("owner info: \ntype: " + owner.getClass().getName() + ", \nuuid: " + owner.getUuid() + ",\n property name for collection: " + ownerPropertyName); throw new CallbackException( "Could not find the property on owner object that corresponds to the collection being processed."); } //now we know this needs to be processed. Proceed accordingly: if (collection instanceof PersistentSet || collection instanceof PersistentList || collection instanceof PersistentMap) { processPersistentCollection(collection, key, action, originalRecordUuid, owner, ownerPropertyName); } return; }
From source file:org.openmrs.module.sync.api.db.hibernate.HibernateSyncInterceptor.java
License:Open Source License
/** * Processes changes to persistent collection that contains instances of OpenmrsObject objects. * <p>//from w ww . ja v a 2 s .com * Remarks: * <p> * Xml 'schema' for the sync item content for the persisted collection follows. Note that for persisted * collections syncItemKey is a composite of owner object uuid and the property name that contains the * collection. <br/> * <persistent-collection> element: wrapper element <br/> * <owner uuid='' propertyName='' type='' action='recreate|update' > element: this * captures the information about the object that holds reference to the collection being * processed <br/> * -uuid: owner object uuid <br/> * -properyName: names of the property on owner object that holds this collection <br/> * -type: owner class name <br/> * -action: recreate, update -- these are collection events defined by hibernate interceptor <br/> * <entry action='update|delete' uuid='' type='' > element: this captures info about * individual collection entries: <br/> * -action: what is being done to this item of the collection: delete (item was removed from the * collection) or update (item was added to the collection) <br/> * -uuid: entry's uuid <br/> * -type: class name * * @param collection Instance of Hibernate AbstractPersistentCollection to process. * @param key key of owner for the collection. * @param action action being performed on the collection: update, recreate */ private void processPersistentCollection(AbstractPersistentCollection collection, Serializable key, String action, String originalRecordUuid, OpenmrsObject owner, String ownerPropertyName) { LinkedHashMap<String, OpenmrsObject> entriesHolder = null; // Setup the serialization data structures to hold the state Package pkg = new Package(); entriesHolder = new LinkedHashMap<String, OpenmrsObject>(); try { CollectionMetadata collMD = getCollectionMetadata(owner.getClass(), ownerPropertyName, getSessionFactory()); if (collMD == null) { throw new SyncException( "Can't find a collection with " + ownerPropertyName + " in class " + owner.getClass()); } Class<?> elementClass = collMD.getElementType().getReturnedClass(); //If this is a simple type like Integer, serialization of the collection will be as below: //<org.openmrs.Cohort> // <memberIds type="java.util.Set(org.openmrs.Cohort)">[2, 3]</memberIds> // ............. and more //This should work just fine as long as there is a Normalizer registered for it if (!OpenmrsObject.class.isAssignableFrom(elementClass) && SyncUtil.getNormalizer(elementClass) != null) { //Check if there is already a NEW/UPDATE sync item for the owner SyncItem syncItem = new SyncItem(); syncItem.setKey(new SyncItemKey<String>(owner.getUuid(), String.class)); syncItem.setContainedType(owner.getClass()); syncItem.setState(SyncItemState.UPDATED); boolean ownerHasSyncItem = getSyncRecord().hasSyncItem(syncItem); syncItem.setState(SyncItemState.NEW); if (!ownerHasSyncItem) ownerHasSyncItem = getSyncRecord().hasSyncItem(syncItem); if (!ownerHasSyncItem) { ClassMetadata cmd = getSessionFactory().getClassMetadata(owner.getClass()); //create an UPDATE sync item for the owner so that the collection changes get recorded along Serializable primaryKeyValue = cmd.getIdentifier(owner, (SessionImplementor) getSessionFactory().getCurrentSession()); packageObject(owner, cmd.getPropertyValues(owner, EntityMode.POJO), cmd.getPropertyNames(), cmd.getPropertyTypes(), primaryKeyValue, SyncItemState.UPDATED); } else { //There is already an UPDATE OR NEW SyncItem for the owner containing the above updates } return; } // find out what entries need to be serialized for (Object entry : (Iterable) collection) { if (entry instanceof OpenmrsObject) { OpenmrsObject obj = (OpenmrsObject) entry; // attempt to retrieve entry uuid String entryUuid = obj.getUuid(); if (entryUuid == null) { entryUuid = fetchUuid(obj); if (log.isDebugEnabled()) { log.debug("Entry uuid was null, attempted to fetch uuid with the following results"); log.debug("Entry type:" + obj.getClass().getName() + ",uuid:" + entryUuid); } } // well, this is messed up: have an instance of // OpenmrsObject but has no uuid if (entryUuid == null) { log.error("Cannot handle collection entries where uuid is null."); throw new CallbackException("Cannot handle collection entries where uuid is null."); } // add it to the holder to avoid possible duplicates: key = // uuid + action entriesHolder.put(entryUuid + "|update", obj); } else { log.warn( "Cannot handle collections where entries are not OpenmrsObject and have no Normalizers. Type was " + entry.getClass() + " in property " + ownerPropertyName + " in class " + owner.getClass()); // skip out early because we don't want to write any xml for it // it was handled by the normal property writer hopefully return; } } // add on deletes if (!"recreate".equals(action) && collection.getRole() != null) { org.hibernate.persister.collection.CollectionPersister persister = ((org.hibernate.engine.SessionFactoryImplementor) getSessionFactory()) .getCollectionPersister(collection.getRole()); Iterator it = collection.getDeletes(persister, false); if (it != null) { while (it.hasNext()) { Object entryDelete = it.next(); if (entryDelete instanceof OpenmrsObject) { OpenmrsObject objDelete = (OpenmrsObject) entryDelete; // attempt to retrieve entry uuid String entryDeleteUuid = objDelete.getUuid(); if (entryDeleteUuid == null) { entryDeleteUuid = fetchUuid(objDelete); if (log.isDebugEnabled()) { log.debug( "Entry uuid was null, attempted to fetch uuid with the following results"); log.debug("Entry type:" + entryDeleteUuid.getClass().getName() + ",uuid:" + entryDeleteUuid); } } // well, this is messed up: have an instance of // OpenmrsObject but has no uuid if (entryDeleteUuid == null) { log.error("Cannot handle collection delete entries where uuid is null."); throw new CallbackException( "Cannot handle collection delete entries where uuid is null."); } // add it to the holder to avoid possible // duplicates: key = uuid + action // also, only add if there is no update action for the same object: see SYNC-280 if (!entriesHolder.containsKey(entryDeleteUuid + "|update")) { entriesHolder.put(entryDeleteUuid + "|delete", objDelete); } } else { // TODO: more debug info log.warn( "Cannot handle collections where entries are not OpenmrsObject and have no Normalizers!"); // skip out early because we don't want to write any // xml for it. it // was handled by the normal property writer // hopefully return; } } } } /* * Create SyncItem and store change in SyncRecord kept in * ThreadLocal. note: when making SyncItemKey, make it a composite * string of uuid + prop. name to avoid collisions with updates to * parent object or updates to more than one collection on same * owner */ // Setup the serialization data structures to hold the state Record xml = pkg.createRecordForWrite(collection.getClass().getName()); Item entityItem = xml.getRootItem(); // serialize owner info: we will need type, prop name where collection // goes, and owner uuid Item item = xml.createItem(entityItem, "owner"); item.setAttribute("type", this.getType(owner)); item.setAttribute("properyName", ownerPropertyName); item.setAttribute("action", action); item.setAttribute("uuid", owner.getUuid()); // build out the xml for the item content Boolean hasNoAutomaticPrimaryKey = null; String type = null; for (String entryKey : entriesHolder.keySet()) { OpenmrsObject entryObject = entriesHolder.get(entryKey); if (type == null) { type = this.getType(entryObject); hasNoAutomaticPrimaryKey = SyncUtil.hasNoAutomaticPrimaryKey(type); } Item temp = xml.createItem(entityItem, "entry"); temp.setAttribute("type", type); temp.setAttribute("action", entryKey.substring(entryKey.indexOf('|') + 1)); temp.setAttribute("uuid", entryObject.getUuid()); if (hasNoAutomaticPrimaryKey) { temp.setAttribute("primaryKey", getSyncService().getPrimaryKey(entryObject)); } } SyncItem syncItem = new SyncItem(); syncItem.setKey(new SyncItemKey<String>(owner.getUuid() + "|" + ownerPropertyName, String.class)); syncItem.setState(SyncItemState.UPDATED); syncItem.setContainedType(collection.getClass()); syncItem.setContent(xml.toStringAsDocumentFragement()); getSyncRecord().addOrRemoveAndAddItem(syncItem); getSyncRecord().addContainedClass(owner.getClass().getName()); // do the original uuid dance, same as in packageObject if (getSyncRecord().getOriginalUuid() == null || "".equals(getSyncRecord().getOriginalUuid())) { getSyncRecord().setOriginalUuid(originalRecordUuid); } } catch (Exception ex) { log.error("Error processing Persistent collection, see callstack and inner expection", ex); throw new CallbackException( "Error processing Persistent collection, see callstack and inner expection.", ex); } }
From source file:org.opennms.netmgt.dao.hibernate.AbstractDaoHibernate.java
License:Open Source License
/** * <p>Parse the {@link DataAccessException} to see if special problems were * encountered while performing the query. See issue NMS-5029 for examples of * stack traces that can be thrown from these calls.</p> * {@see http://issues.opennms.org/browse/NMS-5029} *//*from ww w . ja v a 2 s .c om*/ private void logExtraSaveOrUpdateExceptionInformation(final T entity, final DataAccessException e) { Throwable cause = e; while (cause.getCause() != null) { if (cause.getMessage() != null) { if (cause.getMessage().contains("duplicate key value violates unique constraint")) { final ClassMetadata meta = getSessionFactory().getClassMetadata(m_entityClass); LOG.warn("Duplicate key constraint violation, class: {}, key value: {}", m_entityClass.getName(), meta.getPropertyValue(entity, meta.getIdentifierPropertyName(), EntityMode.POJO)); break; } else if (cause.getMessage().contains("given object has a null identifier")) { LOG.warn("Null identifier on object, class: {}: {}", m_entityClass.getName(), entity.toString()); break; } } cause = cause.getCause(); } }
From source file:org.postgis.hibernate.ContainsExpression.java
License:Open Source License
public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { return new TypedValue[] { new TypedValue(Hibernate.custom(GeometryType.class), geom, EntityMode.POJO) }; }
From source file:org.projectforge.database.xstream.HibernateXmlConverter.java
License:Open Source License
/** * @param writer/*www . j av a 2 s .c om*/ * @param includeHistory * @param session * @throws DataAccessException * @throws HibernateException */ private void writeObjects(final Writer writer, final boolean includeHistory, final Session session, final boolean preserveIds) throws DataAccessException, HibernateException { // Container fr die Objekte final List<Object> all = new ArrayList<Object>(); final XStream stream = initXStream(session, true); final XStream defaultXStream = initXStream(session, false); session.flush(); // Alles laden List<?> list = session.createQuery("select o from java.lang.Object o").setReadOnly(true).list(); list = (List<?>) CollectionUtils.select(list, PredicateUtils.uniquePredicate()); final int size = list.size(); log.info("Writing " + size + " objects"); for (final Iterator<?> it = list.iterator(); it.hasNext();) { final Object obj = it.next(); if (log.isDebugEnabled()) { log.debug("loaded object " + obj); } if ((obj instanceof HistoryEntry || obj instanceof PropertyDelta) && includeHistory == false) { continue; } Hibernate.initialize(obj); Class<?> targetClass = obj.getClass(); while (Enhancer.isEnhanced(targetClass) == true) { targetClass = targetClass.getSuperclass(); } final ClassMetadata classMetadata = session.getSessionFactory().getClassMetadata(targetClass); if (classMetadata == null) { log.fatal("Can't init " + obj + " of type " + targetClass); continue; } // initalisierung des Objekts... defaultXStream.marshal(obj, new CompactWriter(new NullWriter())); if (preserveIds == false) { // Nun kann die ID gelscht werden classMetadata.setIdentifier(obj, null, EntityMode.POJO); } if (log.isDebugEnabled()) { log.debug("loading evicted object " + obj); } if (this.ignoreFromTopLevelListing.contains(targetClass) == false) { all.add(obj); } } // und schreiben try { writer.write("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n"); } catch (final IOException ex) { // ignore, will fail on stream.marshal() } log.info("Wrote " + all.size() + " objects"); final MarshallingStrategy marshallingStrategy = new ProxyIdRefMarshallingStrategy(); stream.setMarshallingStrategy(marshallingStrategy); stream.marshal(all, new PrettyPrintWriter(writer)); }
From source file:org.projectforge.framework.persistence.xstream.HibernateXmlConverter.java
License:Open Source License
/** * @param writer/*from ww w . j a v a 2 s. com*/ * @param includeHistory * @param session * @throws DataAccessException * @throws HibernateException */ private void writeObjects(final Writer writer, final boolean includeHistory, final Session session, final boolean preserveIds) throws DataAccessException, HibernateException { // Container fr die Objekte final List<Object> all = new ArrayList<Object>(); final XStream stream = initXStream(session, true); final XStream defaultXStream = initXStream(session, false); session.flush(); // Alles laden // final List<Class<?>> entities = new ArrayList<Class<?>>(); final List<Class<?>> entities = PfEmgrFactory.get().getMetadataRepository().getTableEntities().stream() .map((e) -> e.getJavaType()).collect(Collectors.toList()); // entities.addAll(HibernateEntities.instance().getOrderedEntities()); // entities.addAll(HibernateEntities.instance().getOrderedHistoryEntities()); for (final Class<?> entityClass : entities) { final String entitySimpleName = entityClass.getSimpleName(); final String entityType = entityClass.getName(); if (includeHistory == false && entityType.startsWith("org.projectforge.framework.persistence.history.entities.") == true) { // Skip history entries. continue; } List<?> list = session.createQuery("select o from " + entityType + " o").setReadOnly(true).list(); list = (List<?>) CollectionUtils.select(list, PredicateUtils.uniquePredicate()); final int size = list.size(); log.info("Writing " + size + " objects"); for (final Iterator<?> it = list.iterator(); it.hasNext();) { final Object obj = it.next(); if (log.isDebugEnabled()) { log.debug("loaded object " + obj); } Hibernate.initialize(obj); final Class<?> targetClass = HibernateProxyHelper.getClassWithoutInitializingProxy(obj); final ClassMetadata classMetadata = session.getSessionFactory().getClassMetadata(targetClass); if (classMetadata == null) { log.fatal("Can't init " + obj + " of type " + targetClass); continue; } // initalisierung des Objekts... defaultXStream.marshal(obj, new CompactWriter(new NullWriter())); if (preserveIds == false) { // Nun kann die ID gelscht werden HibernateCompatUtils.setClassMetaDataSetIdentifier(classMetadata, obj, EntityMode.POJO); } if (log.isDebugEnabled()) { log.debug("loading evicted object " + obj); } if (this.ignoreFromTopLevelListing.contains(targetClass) == false) { all.add(obj); } } } // und schreiben try { writer.write("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n"); } catch (final IOException ex) { // ignore, will fail on stream.marshal() } log.info("Wrote " + all.size() + " objects"); final MarshallingStrategy marshallingStrategy = new ProxyIdRefMarshallingStrategy(); stream.setMarshallingStrategy(marshallingStrategy); stream.marshal(all, new PrettyPrintWriter(writer)); }
From source file:org.riotfamily.common.hibernate.ActiveRecordClassExposer.java
License:Apache License
@SuppressWarnings("unchecked") public void postProcessConfiguration(Configuration config) throws IOException, TemplateException { TemplateHashModel statics = getBeansWrapper(config).getStaticModels(); Collection<ClassMetadata> allMetadata = sessionFactory.getAllClassMetadata().values(); for (ClassMetadata meta : allMetadata) { Class mappedClass = meta.getMappedClass(EntityMode.POJO); if (ActiveRecord.class.isAssignableFrom(mappedClass)) { String key = ClassUtils.getShortName(mappedClass); if (config.getSharedVariable(key) != null) { log.warn("Another shared variable with the name '{}'" + " already exist. Use statics[\"{}\"] in your" + " FreeMarker templates to access the static" + " methods of your ActiveRecord class.", key, mappedClass.getName()); } else { TemplateModel tm = statics.get(mappedClass.getName()); config.setSharedVariable(key, tm); }//from w w w. jav a 2 s .c o m } } }
From source file:org.riotfamily.common.hibernate.ActiveRecordUtils.java
License:Apache License
/** * Returns the identifier of the given ActiveRecord. The id is obtained * using the Hibernate meta-data API.// w ww. j av a 2s. c om * * @see ClassMetadata#getIdentifier(Object, EntityMode) */ public static Serializable getId(ActiveRecord record) { SessionFactory sessionFactory = ActiveRecord.getSessionFactory(); if (sessionFactory == null) { return "N/A"; } return sessionFactory.getClassMetadata(getClass(record)).getIdentifier(record, EntityMode.POJO); }
From source file:org.riotfamily.common.hibernate.HibernateUtils.java
License:Apache License
public static Serializable getId(SessionFactory sessionFactory, Object bean) { Class<?> clazz = Hibernate.getClass(bean); ClassMetadata metadata = sessionFactory.getClassMetadata(clazz); return metadata.getIdentifier(bean, EntityMode.POJO); }
From source file:org.seasar.hibernate.jpa.metadata.HibernateAttributeDesc.java
License:Apache License
public Object getValue(final Object entity) { if (id) {/*from w w w .jav a 2 s. co m*/ return metadata.getIdentifier(entity, EntityMode.POJO); } return metadata.getPropertyValue(entity, name, EntityMode.POJO); }