List of usage examples for org.hibernate Session merge
Object merge(Object object);
From source file:com.evolveum.midpoint.repo.sql.helpers.SequenceHelper.java
License:Apache License
public long advanceSequenceAttempt(String oid, OperationResult result) throws ObjectNotFoundException, SchemaException, SerializationRelatedException { long returnValue; LOGGER.debug("Advancing sequence with oid '{}'.", oid); LOGGER_PERFORMANCE.debug("> advance sequence, oid={}", oid); Session session = null; try {/* w ww . ja v a 2 s . com*/ session = baseHelper.beginTransaction(); PrismObject<SequenceType> prismObject = objectRetriever.getObjectInternal(session, SequenceType.class, oid, null, true, result); if (LOGGER.isTraceEnabled()) { LOGGER.trace("OBJECT before:\n{}", prismObject.debugDump()); } SequenceType sequence = prismObject.asObjectable(); if (!sequence.getUnusedValues().isEmpty()) { returnValue = sequence.getUnusedValues().remove(0); } else { long counter = sequence.getCounter() != null ? sequence.getCounter() : 0L; long maxCounter = sequence.getMaxCounter() != null ? sequence.getMaxCounter() : Long.MAX_VALUE; boolean allowRewind = Boolean.TRUE.equals(sequence.isAllowRewind()); if (counter < maxCounter) { returnValue = counter; sequence.setCounter(counter + 1); } else if (counter == maxCounter) { returnValue = counter; if (allowRewind) { sequence.setCounter(0L); } else { sequence.setCounter(counter + 1); // will produce exception during next run } } else { // i.e. counter > maxCounter if (allowRewind) { // shouldn't occur but... LOGGER.warn("Sequence {} overflown with allowRewind set to true. Rewinding.", oid); returnValue = 0; sequence.setCounter(1L); } else { // TODO some better exception... throw new SystemException( "No (next) value available from sequence " + oid + ". Current counter = " + sequence.getCounter() + ", max value = " + sequence.getMaxCounter()); } } } if (LOGGER.isTraceEnabled()) { LOGGER.trace("Return value = {}, OBJECT after:\n{}", returnValue, prismObject.debugDump()); } // merge and update object LOGGER.trace("Translating JAXB to data type."); RObject rObject = objectUpdater.createDataObjectFromJAXB(prismObject, PrismIdentifierGenerator.Operation.MODIFY); rObject.setVersion(rObject.getVersion() + 1); objectUpdater.updateFullObject(rObject, prismObject); session.merge(rObject); LOGGER.trace("Before commit..."); session.getTransaction().commit(); LOGGER.trace("Committed!"); return returnValue; } catch (ObjectNotFoundException ex) { baseHelper.rollbackTransaction(session, ex, result, true); throw ex; } catch (SchemaException ex) { baseHelper.rollbackTransaction(session, ex, result, true); throw ex; } catch (DtoTranslationException | RuntimeException ex) { baseHelper.handleGeneralException(ex, session, result); // should always throw an exception throw new SystemException("Exception " + ex + " was not handled correctly", ex); // ...so this shouldn't occur at all } finally { baseHelper.cleanupSessionAndResult(session, result); LOGGER.trace("Session cleaned up."); } }
From source file:com.evolveum.midpoint.repo.sql.helpers.SequenceHelper.java
License:Apache License
public void returnUnusedValuesToSequenceAttempt(String oid, Collection<Long> unusedValues, OperationResult result) throws ObjectNotFoundException, SchemaException, SerializationRelatedException { LOGGER.debug("Returning unused values of {} to a sequence with oid '{}'.", unusedValues, oid); LOGGER_PERFORMANCE.debug("> return unused values, oid={}, values={}", oid, unusedValues); Session session = null; try {/*from w ww.jav a 2 s .com*/ session = baseHelper.beginTransaction(); PrismObject<SequenceType> prismObject = objectRetriever.getObjectInternal(session, SequenceType.class, oid, null, true, result); if (LOGGER.isTraceEnabled()) { LOGGER.trace("OBJECT before:\n{}", prismObject.debugDump()); } SequenceType sequence = prismObject.asObjectable(); int maxUnusedValues = sequence.getMaxUnusedValues() != null ? sequence.getMaxUnusedValues() : 0; Iterator<Long> valuesToReturnIterator = unusedValues.iterator(); while (valuesToReturnIterator.hasNext() && sequence.getUnusedValues().size() < maxUnusedValues) { Long valueToReturn = valuesToReturnIterator.next(); if (valueToReturn == null) { // sanity check continue; } if (!sequence.getUnusedValues().contains(valueToReturn)) { sequence.getUnusedValues().add(valueToReturn); } else { LOGGER.warn( "UnusedValues in sequence {} already contains value of {} - ignoring the return request", oid, valueToReturn); } } if (LOGGER.isTraceEnabled()) { LOGGER.trace("OBJECT after:\n{}", prismObject.debugDump()); } // merge and update object LOGGER.trace("Translating JAXB to data type."); RObject rObject = objectUpdater.createDataObjectFromJAXB(prismObject, PrismIdentifierGenerator.Operation.MODIFY); rObject.setVersion(rObject.getVersion() + 1); objectUpdater.updateFullObject(rObject, prismObject); session.merge(rObject); LOGGER.trace("Before commit..."); session.getTransaction().commit(); LOGGER.trace("Committed!"); } catch (ObjectNotFoundException ex) { baseHelper.rollbackTransaction(session, ex, result, true); throw ex; } catch (SchemaException ex) { baseHelper.rollbackTransaction(session, ex, result, true); throw ex; } catch (DtoTranslationException | RuntimeException ex) { baseHelper.handleGeneralException(ex, session, result); // should always throw an exception throw new SystemException("Exception " + ex + " was not handled correctly", ex); // ...so this shouldn't occur at all } finally { baseHelper.cleanupSessionAndResult(session, result); LOGGER.trace("Session cleaned up."); } }
From source file:com.evolveum.midpoint.repo.sql.SqlRepositoryServiceImpl.java
License:Apache License
private <T extends ObjectType> String overwriteAddObjectAttempt(PrismObject<T> object, ObjectType objectType, RObject rObject, String originalOid, Session session) throws ObjectAlreadyExistsException, SchemaException, DtoTranslationException { //check if object already exists, find differences and increment version if necessary Collection<? extends ItemDelta> modifications = null; if (originalOid != null) { try {/*from www .j ava 2s . c om*/ PrismObject<T> oldObject = getObject(session, object.getCompileTimeClass(), originalOid, null, true); ObjectDelta<T> delta = object.diff(oldObject); modifications = delta.getModifications(); //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) { 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); //todo finish orgClosureManager // orgClosureManager.updateOrgClosure(modifications, session, merged.getOid(), object.getCompileTimeClass(), // OrgClosureManager.Operation.ADD); //update org. unit hierarchy based on modifications if (modifications == null || modifications.isEmpty()) { //we're not overwriting object - we fill new hierarchy if (objectType instanceof OrgType || !objectType.getParentOrgRef().isEmpty()) { long time = System.currentTimeMillis(); LOGGER.trace("Org. structure closure table update started."); objectType.setOid(merged.getOid()); fillHierarchy(merged, session, true); LOGGER.trace("Org. structure closure table update finished ({} ms).", new Object[] { (System.currentTimeMillis() - time) }); } } else { //we have to recompute actual hierarchy because we've changed object recomputeHierarchy(merged, session, modifications); } return merged.getOid(); }
From source file:com.evolveum.midpoint.repo.sql.SqlRepositoryServiceImpl.java
License:Apache License
private <T extends ObjectType> void modifyObjectAttempt(Class<T> type, String oid, Collection<? extends ItemDelta> modifications, OperationResult result) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { LOGGER.debug("Modifying object '{}' with oid '{}'.", new Object[] { type.getSimpleName(), oid }); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Modifications:\n{}", new Object[] { DebugUtil.debugDump(modifications) }); }/*from ww w . ja v a 2 s . c o m*/ Session session = null; try { session = beginTransaction(); // get user PrismObject<T> prismObject = getObject(session, type, oid, null, true); // apply diff if (LOGGER.isTraceEnabled()) { LOGGER.trace("OBJECT before:\n{}", new Object[] { prismObject.debugDump() }); } ItemDelta.applyTo(modifications, prismObject); if (LOGGER.isTraceEnabled()) { LOGGER.trace("OBJECT after:\n{}", prismObject.debugDump()); } // merge and update user LOGGER.trace("Translating JAXB to data type."); RObject rObject = createDataObjectFromJAXB(prismObject, false); rObject.setVersion(rObject.getVersion() + 1); updateFullObject(rObject, prismObject); session.merge(rObject); //todo finish orgClosureManager //orgClosureManager.updateOrgClosure(modifications, session, oid, type, OrgClosureManager.Operation.MODIFY); recomputeHierarchy(rObject, session, modifications); LOGGER.trace("Before commit..."); session.getTransaction().commit(); LOGGER.trace("Committed!"); } catch (ObjectNotFoundException ex) { rollbackTransaction(session, ex, result, true); throw ex; } catch (ConstraintViolationException ex) { 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) { rollbackTransaction(session, ex, result, true); throw ex; } catch (QueryException | DtoTranslationException | RuntimeException ex) { handleGeneralException(ex, session, result); } finally { cleanupSessionAndResult(session, result); LOGGER.trace("Session cleaned up."); } }
From source file:com.example.app.model.DemoUserProfileDAO.java
License:Open Source License
/** * Save UserProfile.//from w w w . ja va2 s. com * * @param demoUserProfile the user profile to save. */ public void saveUserProfile(DemoUserProfile demoUserProfile) { beginTransaction(); boolean success = false; try { final long id = demoUserProfile.getId(); String name = demoUserProfile.getName().getLast() + ", " + demoUserProfile.getName().getFirst(); String pictureName = name + " #" + id; final Session session = getSession(); FileEntity picture = demoUserProfile.getPicture(); if (picture != null) { pictureName += getExtensionWithDot(picture); TemporaryFileEntity tfe = null; if (picture instanceof TemporaryFileEntity) tfe = (TemporaryFileEntity) picture; ByteSource fileData = tfe != null ? tfe.asByteSource() : ByteSource.empty(); // Ensure our picture file has a unique file name consistent with the profile. if (picture.getId() < 1) { final CmsSite site = demoUserProfile.getSite(); final DirectoryEntity rootDirectory = FileSystemDirectory.getRootDirectory(site); DirectoryEntity parentDirectory = _fileSystemDAO.mkdirs(rootDirectory, null, "UserProfilePictures"); picture.setName(pictureName); picture = _fileSystemDAO.store(new StoreRequest(parentDirectory, picture, fileData) .withCreateMode(overwrite).withRequest(Event.getRequest())); demoUserProfile.setPicture(picture); } else { EntityRetriever er = EntityRetriever.getInstance(); picture = er.reattachIfNecessary(tfe != null ? tfe.getFileEntity() : picture); picture.setName(pictureName); _fileSystemDAO.store(new StoreRequest(picture, fileData).withCreateMode(overwrite) .withRequest(Event.getRequest())); demoUserProfile.setPicture(picture); // In case we are cascading. if (tfe != null) tfe.deleteStream(); } } if (isTransient(demoUserProfile) || isAttached(demoUserProfile)) session.saveOrUpdate(demoUserProfile); else session.merge(demoUserProfile); if (picture != null && id == 0) { // New user profile. Update picture name to include the ID pictureName = name + " #" + demoUserProfile.getId() + getExtensionWithDot(picture); picture.setName(pictureName); _fileSystemDAO.store(new StoreRequest(picture)); } success = true; } catch (HibernateException ioe) { throw new RuntimeException("Unable to access filesystem.", ioe); } finally { if (success) commitTransaction(); else recoverableRollbackTransaction(); } }
From source file:com.example.app.model.UserProfileDAO.java
License:Open Source License
/** * Save UserProfile./* w w w . j a v a 2s .c o m*/ * * @param userProfile the user profile to save. */ public void saveUserProfile(UserProfile userProfile) { beginTransaction(); boolean success = false; try { final long id = userProfile.getId(); String name = userProfile.getName().getLast() + ", " + userProfile.getName().getFirst(); String pictureName = name + " #" + id; final Session session = getSession(); FileEntity picture = userProfile.getPicture(); if (picture != null) { pictureName += getExtensionWithDot(picture); TemporaryFileEntity tfe = null; if (picture instanceof TemporaryFileEntity) tfe = (TemporaryFileEntity) picture; ByteSource fileData = tfe != null ? tfe.asByteSource() : ByteSource.empty(); // Ensure our picture file has a unique file name consistent with the profile. if (picture.getId() < 1) { final CmsSite site = userProfile.getSite(); final DirectoryEntity rootDirectory = FileSystemDirectory.getRootDirectory(site); DirectoryEntity parentDirectory = _fileSystemDAO.mkdirs(rootDirectory, null, "UserProfilePictures"); picture.setName(pictureName); picture = _fileSystemDAO.store(new StoreRequest(parentDirectory, picture, fileData) .withCreateMode(overwrite).withRequest(Event.getRequest())); userProfile.setPicture(picture); } else { EntityRetriever er = EntityRetriever.getInstance(); picture = er.reattachIfNecessary(tfe != null ? tfe.getFileEntity() : picture); picture.setName(pictureName); _fileSystemDAO.store(new StoreRequest(picture, fileData).withCreateMode(overwrite) .withRequest(Event.getRequest())); userProfile.setPicture(picture); // In case we are cascading. if (tfe != null) tfe.deleteStream(); } } if (isTransient(userProfile) || isAttached(userProfile)) session.saveOrUpdate(userProfile); else session.merge(userProfile); if (picture != null && id == 0) { // New user profile. Update picture name to include the ID pictureName = name + " #" + userProfile.getId() + getExtensionWithDot(picture); picture.setName(pictureName); _fileSystemDAO.store(new StoreRequest(picture)); } success = true; } catch (HibernateException ioe) { throw new RuntimeException("Unable to access filesystem.", ioe); } finally { if (success) commitTransaction(); else recoverableRollbackTransaction(); } }
From source file:com.facultyshowcase.app.model.ProfessorProfileDAO.java
License:Open Source License
/** * Save ProfessorProfile.// w ww . j a v a 2 s . com * * @param ProfessorProfile the user profile to save. */ @WithTransaction public void saveProfessorProfile(ProfessorProfile ProfessorProfile) { try { final long id = ProfessorProfile.getId(); String name = ProfessorProfile.getName().getLast() + ", " + ProfessorProfile.getName().getFirst(); String pictureName = name + " #" + id; final Session session = getSession(); FileEntity picture = ProfessorProfile.getPicture(); if (picture != null) { pictureName += _getFileExtensionWithDot(picture); // Ensure our picture file has a unique file name consistent with the profile. if (picture.getId() < 1) { final CmsSite site = ProfessorProfile.getSite(); final DirectoryEntity rootDirectory = FileSystemDirectory.getRootDirectory(site); DirectoryEntity parentDirectory = _fileSystemDAO.mkdirs(rootDirectory, null, "ProfessorProfilePictures"); picture.setName(pictureName); picture = _fileSystemDAO.newFile(parentDirectory, picture, FileSystemEntityCreateMode.truncate); ProfessorProfile.setPicture(picture); } else if (picture instanceof TemporaryFileEntity) { TemporaryFileEntity tfe = (TemporaryFileEntity) picture; EntityRetriever er = EntityRetriever.getInstance(); picture = er.reattachIfNecessary(tfe.getFileEntity()); picture.setName(pictureName); _fileSystemDAO.update(picture); _fileSystemDAO.setStream(picture, tfe.getStream(), true); ProfessorProfile.setPicture(picture); // In case we are cascading. tfe.deleteStream(); } } ProfessorProfile.setLastModTime(new Date()); if (isTransient(ProfessorProfile) || isAttached(ProfessorProfile)) session.saveOrUpdate(ProfessorProfile); else session.merge(ProfessorProfile); if (picture != null && id == 0) { // New user profile. Update picture name to include the ID pictureName = name + " #" + ProfessorProfile.getId() + _getFileExtensionWithDot(picture); picture.setName(pictureName); _fileSystemDAO.update(picture); } } catch (IOException ioe) { throw new RuntimeException("Unable to access filesystem.", ioe); } }
From source file:com.floreantpos.model.dao.MenuItemDAO.java
License:Open Source License
public MenuItem initialize(MenuItem menuItem) { if (menuItem == null || menuItem.getId() == null) return menuItem; Session session = null; try {/*from ww w .jav a2s . c o m*/ session = createNewSession(); menuItem = (MenuItem) session.merge(menuItem); Hibernate.initialize(menuItem.getMenuItemModiferGroups()); List<MenuItemModifierGroup> menuItemModiferGroups = menuItem.getMenuItemModiferGroups(); if (menuItemModiferGroups != null) { for (MenuItemModifierGroup menuItemModifierGroup : menuItemModiferGroups) { Hibernate.initialize(menuItemModifierGroup.getModifierGroup().getModifiers()); } } Hibernate.initialize(menuItem.getShifts()); return menuItem; } finally { closeSession(session); } }
From source file:com.floreantpos.ui.model.MenuItemForm.java
License:Open Source License
@Override protected void updateView() { MenuItem menuItem = getBean(); if (menuItem.getId() != null && !Hibernate.isInitialized(menuItem.getMenuItemModiferGroups())) { //initialize food item modifer groups. MenuItemDAO dao = new MenuItemDAO(); Session session = dao.getSession(); menuItem = (MenuItem) session.merge(menuItem); Hibernate.initialize(menuItem.getMenuItemModiferGroups()); session.close();/* www . j a v a2s . c o m*/ } // terminalList.selectItems(menuItem.getTerminals()); orderList.selectItems(menuItem.getOrderTypeList()); tfName.setText(menuItem.getName()); tfDescription.setText(menuItem.getDescription()); tfTranslatedName.setText(menuItem.getTranslatedName()); tfBarcode.setText(menuItem.getBarcode()); tfBuyPrice.setText(String.valueOf(menuItem.getBuyPrice())); tfPrice.setText(String.valueOf(menuItem.getPrice())); tfUnitName.setText(menuItem.getUnitName()); tfDiscountRate.setText(String.valueOf(menuItem.getDiscountRate())); tfStockCount.setText(String.valueOf(menuItem.getStockAmount())); chkVisible.setSelected(menuItem.isVisible()); cbShowTextWithImage.setSelected(menuItem.isShowImageOnly()); cbDisableStockCount.setSelected(menuItem.isDisableWhenStockAmountIsZero()); ImageIcon menuItemImage = menuItem.getImage(); if (menuItemImage != null) { lblImagePreview.setIcon(menuItemImage); } cbGroup.setSelectedItem(menuItem.getParent()); cbTax.setSelectedItem(menuItem.getTax()); cbPrinterGroup.setSelectedItem(menuItem.getPrinterGroup()); if (menuItem.getSortOrder() != null) { tfSortOrder.setText(menuItem.getSortOrder().toString()); } Color buttonColor = menuItem.getButtonColor(); if (buttonColor != null) { btnButtonColor.setBackground(buttonColor); btnTextColor.setBackground(buttonColor); } if (menuItem.getTextColor() != null) { btnTextColor.setForeground(menuItem.getTextColor()); } cbFractionalUnit.setSelected(menuItem.isFractionalUnit()); }
From source file:com.floreantpos.ui.model.MenuModifierGroupForm.java
License:Open Source License
@Override protected void updateView() { MenuModifierGroup group = (MenuModifierGroup) getBean(); if (group.getId() != null && !Hibernate.isInitialized(group.getModifiers())) { ModifierDAO dao = new ModifierDAO(); Session session = dao.getSession(); group = (MenuModifierGroup) session.merge(group); Hibernate.initialize(group.getModifiers()); session.close();/*from www.j a v a 2 s . co m*/ } tfName.setText(group.getName()); tfTranslatedName.setText(group.getTranslatedName()); }