List of usage examples for org.hibernate Session merge
Object merge(Object object);
From source file:com.esales.model.CategoriaModel.java
public String update(Categoria obj) { //Abre um sesso Session objSession = this.objSessionFactory.openSession(); //Inicia uma transao dentro da sesso aberta Transaction objTransaction = objSession.beginTransaction(); try {/*from w ww. j av a 2s . c om*/ //ATUALIZA o objeto categoria, assim o hibernate persiste no bancoapagando o registro. objSession.merge(obj); //Realiza um commit do UPDATE objTransaction.commit(); } catch (Exception e) { //Caso ocorrer algum erro, mostra uma mensagem msg = e.getMessage(); //Realiza o Rollback, cancelando o UPDATE no banco de dados. objTransaction.rollback(); } //Fecha a sesso objSession.close(); //Retorna a mensagem return msg; }
From source file:com.esales.model.ModelDAO.java
public String update(SystemUser obj) { //Abre um sesso Session objSession = this.objSessionFactory.openSession(); //Inicia uma transao dentro da sesso aberta Transaction objTransaction = objSession.beginTransaction(); try {/*from w w w.j a va 2 s .co m*/ //ATUALIZA o objeto, assim o hibernate persiste no bancoapagando o registro. objSession.merge(obj); //Realiza um commit do UPDATE objTransaction.commit(); } catch (Exception e) { //Caso ocorrer algum erro, mostra uma mensagem msg = e.getMessage(); //Realiza o Rollback, cancelando o UPDATE no banco de dados. objTransaction.rollback(); } //Fecha a sesso objSession.close(); //Retorna a mensagem return msg; }
From source file:com.esales.model.RacaModel.java
public String update(Raca obj) { //Abre um sesso Session objSession = this.objSessionFactory.openSession(); //Inicia uma transao dentro da sesso aberta Transaction objTransaction = objSession.beginTransaction(); try {/*from www .j a v a 2s .co m*/ //ATUALIZA o objeto categoria, assim o hibernate persiste no bancoapagando o registro. objSession.merge(obj); //Realiza um commit do UPDATE objTransaction.commit(); } catch (Exception e) { //Caso ocorrer algum erro, mostra uma mensagem msg = e.getMessage(); //Realiza o Rollback, cancelando o UPDATE no banco de dados. objTransaction.rollback(); } //Fecha a sesso objSession.close(); //Retorna a mensagem return msg; }
From source file:com.esales.model.UsuarioModel.java
public String update(Usuario obj) { //Abre um sesso Session objSession = this.objSessionFactory.openSession(); //Inicia uma transao dentro da sesso aberta Transaction objTransaction = objSession.beginTransaction(); try {/*from w ww . j a va2 s .c om*/ //ATUALIZA o objeto, assim o hibernate persiste no bancoapagando o registro. objSession.merge(obj); //Realiza um commit do UPDATE objTransaction.commit(); } catch (Exception e) { //Caso ocorrer algum erro, mostra uma mensagem msg = e.getMessage(); //Realiza o Rollback, cancelando o UPDATE no banco de dados. objTransaction.rollback(); } //Fecha a sesso objSession.close(); //Retorna a mensagem return msg; }
From source file:com.esales.model.UsuarioTipoModel.java
public String update(UsuarioTipo obj) { //Abre um sesso Session objSession = this.objSessionFactory.openSession(); //Inicia uma transao dentro da sesso aberta Transaction objTransaction = objSession.beginTransaction(); try {//from w w w .j av a 2 s . co m //ATUALIZA o objeto, assim o hibernate persiste no bancoapagando o registro. objSession.merge(obj); //Realiza um commit do UPDATE objTransaction.commit(); } catch (Exception e) { //Caso ocorrer algum erro, mostra uma mensagem msg = e.getMessage(); //Realiza o Rollback, cancelando o UPDATE no banco de dados. objTransaction.rollback(); } //Fecha a sesso objSession.close(); //Retorna a mensagem return msg; }
From source file:com.evolveum.midpoint.repo.sql.helpers.CertificationCaseHelper.java
License:Apache License
private void updateCasesContent(Session session, String campaignOid, Collection<? extends ItemDelta> modifications, List<Long> casesAddedOrDeleted, RepoModifyOptions modifyOptions) throws SchemaException, ObjectNotFoundException, DtoTranslationException { Set<Long> casesModified = new HashSet<>(); for (ItemDelta delta : modifications) { ItemPath deltaPath = delta.getPath(); if (deltaPath.size() > 1) { LOGGER.trace("Updating campaign " + campaignOid + " with delta " + delta); // should start with "case[id]" long id = checkPathSanity(deltaPath, casesAddedOrDeleted); Query query = session.getNamedQuery("get.campaignCase"); query.setString("ownerOid", campaignOid); query.setInteger("id", (int) id); byte[] fullObject = (byte[]) query.uniqueResult(); if (fullObject == null) { throw new ObjectNotFoundException("Couldn't update cert campaign " + campaignOid + " + by delta with path " + deltaPath + " - specified case does not exist"); }/* www . j av a2 s .co m*/ AccessCertificationCaseType aCase = RAccessCertificationCase.createJaxb(fullObject, prismContext, false); delta = delta.clone(); // to avoid changing original modifications delta.setParentPath(delta.getParentPath().tail(2)); // remove "case[id]" from the delta path delta.applyTo(aCase.asPrismContainerValue()); // we need to generate IDs but we (currently) do not use that for setting "isTransient" flag PrismIdentifierGenerator generator = new PrismIdentifierGenerator(); generator.generate(aCase, PrismIdentifierGenerator.Operation.MODIFY); RAccessCertificationCase rCase = RAccessCertificationCase.toRepo(campaignOid, aCase, prismContext); session.merge(rCase); LOGGER.trace("Access certification case {} merged", rCase); casesModified.add(aCase.getId()); } } // refresh campaign cases, if requested if (RepoModifyOptions.isExecuteIfNoChanges(modifyOptions)) { Query query = session.getNamedQuery("get.campaignCases"); query.setString("ownerOid", campaignOid); List<Object> cases = query.list(); for (Object o : cases) { if (!(o instanceof byte[])) { throw new IllegalStateException("Certification case: expected byte[], got " + o.getClass()); } byte[] fullObject = (byte[]) o; AccessCertificationCaseType aCase = RAccessCertificationCase.createJaxb(fullObject, prismContext, false); Long id = aCase.getId(); if (id != null && casesAddedOrDeleted != null && !casesAddedOrDeleted.contains(id) && !casesModified.contains(id)) { RAccessCertificationCase rCase = RAccessCertificationCase.toRepo(campaignOid, aCase, prismContext); session.merge(rCase); LOGGER.trace("Access certification case {} refreshed", rCase); } } } }
From source file:com.evolveum.midpoint.repo.sql.helpers.LookupTableHelper.java
License:Apache License
public void updateLookupTableData(Session session, String tableOid, Collection<? extends ItemDelta> modifications) throws SchemaException { if (modifications.isEmpty()) { return;// ww w . ja v a 2s . co m } for (ItemDelta delta : modifications) { if (delta.getPath().size() == 1) { // whole row add/delete/replace if (!(delta instanceof ContainerDelta)) { throw new IllegalStateException("Wrong table delta sneaked into updateLookupTableData: class=" + delta.getClass() + ", path=" + delta.getPath()); } // one "table" container modification ContainerDelta containerDelta = (ContainerDelta) delta; if (containerDelta.getValuesToDelete() != null) { // todo do 'bulk' delete like delete from ... where oid=? and id in (...) for (PrismContainerValue<LookupTableRowType> value : (Collection<PrismContainerValue>) containerDelta .getValuesToDelete()) { if (value.getId() != null) { deleteRowById(session, tableOid, value.getId()); } else if (value.asContainerable().getKey() != null) { deleteRowByKey(session, tableOid, value.asContainerable().getKey()); } else { // ignore (or throw an exception?) } } } if (containerDelta.getValuesToAdd() != null) { int currentId = generalHelper.findLastIdInRepo(session, tableOid, "get.lookupTableLastId") + 1; addLookupTableRows(session, tableOid, containerDelta.getValuesToAdd(), currentId, true); } if (containerDelta.getValuesToReplace() != null) { deleteLookupTableRows(session, tableOid); addLookupTableRows(session, tableOid, containerDelta.getValuesToReplace(), 1, false); } } else if (delta.getPath().size() == 3) { // row segment modification (structure is already checked) List<ItemPathSegment> segments = delta.getPath().getSegments(); Long rowId = ((IdItemPathSegment) segments.get(1)).getId(); QName name = ((NameItemPathSegment) segments.get(2)).getName(); RLookupTableRow row = (RLookupTableRow) session.get(RLookupTableRow.class, new RContainerId(RUtil.toInteger(rowId), tableOid)); LookupTableRowType rowType = row.toJAXB(); delta.setParentPath(ItemPath.EMPTY_PATH); delta.applyTo(rowType.asPrismContainerValue()); if (!QNameUtil.match(name, LookupTableRowType.F_LAST_CHANGE_TIMESTAMP)) { rowType.setLastChangeTimestamp(null); // in order to get filled in via toRepo call below } RLookupTableRow rowUpdated = RLookupTableRow.toRepo(tableOid, rowType); session.merge(rowUpdated); } } }
From source file:com.evolveum.midpoint.repo.sql.helpers.ObjectDeltaUpdater.java
License:Apache License
private <T extends ObjectType> RObject<T> merge(RObject<T> object, Session session) { return (RObject) session.merge(object); }
From source file:com.evolveum.midpoint.repo.sql.helpers.ObjectUpdater.java
License:Apache License
private <T extends ObjectType> String overwriteAddObjectAttempt(PrismObject<T> object, RObject rObject, String originalOid, Session session, OrgClosureManager.Context closureContext, OperationResult result) throws ObjectAlreadyExistsException, SchemaException, DtoTranslationException { PrismObject<T> oldObject = null; //check if object already exists, find differences and increment version if necessary Collection<? extends ItemDelta> modifications = null; if (originalOid != null) { try {/*from w w w . j a va2 s . c o m*/ oldObject = objectRetriever.getObjectInternal(session, object.getCompileTimeClass(), originalOid, null, true, result); ObjectDelta<T> delta = object.diff(oldObject); modifications = delta.getModifications(); LOGGER.trace("overwriteAddObjectAttempt: originalOid={}, modifications={}", originalOid, modifications); //we found existing object which will be overwritten, therefore we increment version Integer version = RUtil.getIntegerFromString(oldObject.getVersion()); version = (version == null) ? 0 : ++version; rObject.setVersion(version); // } catch (QueryException ex) { // baseHelper.handleGeneralCheckedException(ex, session, null); } catch (ObjectNotFoundException ex) { //it's ok that object was not found, therefore we won't be overwriting it } } updateFullObject(rObject, object); RObject merged = (RObject) session.merge(rObject); lookupTableHelper.addLookupTableRows(session, rObject, oldObject != null); caseHelper.addCertificationCampaignCases(session, rObject, oldObject != null); if (closureManager.isEnabled()) { OrgClosureManager.Operation operation; if (modifications == null) { operation = OrgClosureManager.Operation.ADD; modifications = createAddParentRefDelta(object); } else { operation = OrgClosureManager.Operation.MODIFY; } closureManager.updateOrgClosure(oldObject, modifications, session, merged.getOid(), object.getCompileTimeClass(), operation, closureContext); } return merged.getOid(); }
From source file:com.evolveum.midpoint.repo.sql.helpers.ObjectUpdater.java
License:Apache License
public <T extends ObjectType> void modifyObjectAttempt(Class<T> type, String oid, Collection<? extends ItemDelta> modifications, RepoModifyOptions modifyOptions, OperationResult result) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException, SerializationRelatedException {//w ww. j av a 2 s . co m // clone - because some certification and lookup table related methods manipulate this collection and even their constituent deltas // TODO clone elements only if necessary modifications = CloneUtil.cloneCollectionMembers(modifications); //modifications = new ArrayList<>(modifications); LOGGER.debug("Modifying object '{}' with oid '{}'.", new Object[] { type.getSimpleName(), oid }); LOGGER_PERFORMANCE.debug("> modify object {}, oid={}, modifications={}", type.getSimpleName(), oid, modifications); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Modifications:\n{}", DebugUtil.debugDump(modifications)); } Session session = null; OrgClosureManager.Context closureContext = null; try { session = baseHelper.beginTransaction(); closureContext = closureManager.onBeginTransactionModify(session, type, oid, modifications); Collection<? extends ItemDelta> lookupTableModifications = lookupTableHelper .filterLookupTableModifications(type, modifications); Collection<? extends ItemDelta> campaignCaseModifications = caseHelper .filterCampaignCaseModifications(type, modifications); if (!modifications.isEmpty() || RepoModifyOptions.isExecuteIfNoChanges(modifyOptions)) { // JpegPhoto (RFocusPhoto) is a special kind of entity. First of all, it is lazily loaded, because photos are really big. // Each RFocusPhoto naturally belongs to one RFocus, so it would be appropriate to set orphanRemoval=true for focus-photo // association. However, this leads to a strange problem when merging in-memory RFocus object with the database state: // If in-memory RFocus object has no photo associated (because of lazy loading), then the associated RFocusPhoto is deleted. // // To prevent this behavior, we've set orphanRemoval to false. Fortunately, the remove operation on RFocus // seems to be still cascaded to RFocusPhoto. What we have to implement ourselves, however, is removal of RFocusPhoto // _without_ removing of RFocus. In order to know whether the photo has to be removed, we have to retrieve // its value, apply the delta (e.g. if the delta is a DELETE VALUE X, we have to know whether X matches current // value of the photo), and if the resulting value is empty, we have to manually delete the RFocusPhoto instance. // // So the first step is to retrieve the current value of photo - we obviously do this only if the modifications // deal with the jpegPhoto property. Collection<SelectorOptions<GetOperationOptions>> options; boolean containsFocusPhotoModification = FocusType.class.isAssignableFrom(type) && containsPhotoModification(modifications); if (containsFocusPhotoModification) { options = Collections.singletonList(SelectorOptions.create(FocusType.F_JPEG_PHOTO, GetOperationOptions.createRetrieve(RetrieveOption.INCLUDE))); } else { options = null; } // get object PrismObject<T> prismObject = objectRetriever.getObjectInternal(session, type, oid, options, true, result); // apply diff if (LOGGER.isTraceEnabled()) { LOGGER.trace("OBJECT before:\n{}", new Object[] { prismObject.debugDump() }); } PrismObject<T> originalObject = null; if (closureManager.isEnabled()) { originalObject = prismObject.clone(); } ItemDelta.applyTo(modifications, prismObject); if (LOGGER.isTraceEnabled()) { LOGGER.trace("OBJECT after:\n{}", prismObject.debugDump()); } // Continuing the photo treatment: should we remove the (now obsolete) focus photo? // We have to test prismObject at this place, because updateFullObject (below) removes photo property from the prismObject. boolean shouldPhotoBeRemoved = containsFocusPhotoModification && ((FocusType) prismObject.asObjectable()).getJpegPhoto() == null; // merge and update object LOGGER.trace("Translating JAXB to data type."); RObject rObject = createDataObjectFromJAXB(prismObject, PrismIdentifierGenerator.Operation.MODIFY); rObject.setVersion(rObject.getVersion() + 1); updateFullObject(rObject, prismObject); LOGGER.trace("Starting merge."); session.merge(rObject); if (closureManager.isEnabled()) { closureManager.updateOrgClosure(originalObject, modifications, session, oid, type, OrgClosureManager.Operation.MODIFY, closureContext); } // JpegPhoto cleanup: As said before, if a focus has to have no photo (after modifications are applied), // we have to remove the photo manually. if (shouldPhotoBeRemoved) { Query query = session.createQuery("delete RFocusPhoto where ownerOid = :oid"); query.setParameter("oid", prismObject.getOid()); query.executeUpdate(); LOGGER.trace("Focus photo for {} was deleted", prismObject.getOid()); } } if (LookupTableType.class.isAssignableFrom(type)) { lookupTableHelper.updateLookupTableData(session, oid, lookupTableModifications); } if (AccessCertificationCampaignType.class.isAssignableFrom(type)) { caseHelper.updateCampaignCases(session, oid, campaignCaseModifications, modifyOptions); } LOGGER.trace("Before commit..."); session.getTransaction().commit(); LOGGER.trace("Committed!"); } catch (ObjectNotFoundException ex) { baseHelper.rollbackTransaction(session, ex, result, true); throw ex; } catch (ConstraintViolationException ex) { handleConstraintViolationException(session, ex, result); baseHelper.rollbackTransaction(session, ex, result, true); LOGGER.debug("Constraint violation occurred (will be rethrown as ObjectAlreadyExistsException).", ex); // we don't know if it's only name uniqueness violation, or something else, // therefore we're throwing it always as ObjectAlreadyExistsException //todo improve (we support only 5 DB, so we should probably do some hacking in here) throw new ObjectAlreadyExistsException(ex); } catch (SchemaException ex) { baseHelper.rollbackTransaction(session, ex, result, true); throw ex; } catch (DtoTranslationException | RuntimeException ex) { baseHelper.handleGeneralException(ex, session, result); } finally { cleanupClosureAndSessionAndResult(closureContext, session, result); LOGGER.trace("Session cleaned up."); } }