Java Code Examples for org.hibernate.Session#saveOrUpdate()

The following examples show how to use org.hibernate.Session#saveOrUpdate() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CourseCreditTypes.java    From unitime with Apache License 2.0 6 votes vote down vote up
protected void update(CourseCreditType credit, Record record, SessionContext context, Session hibSession) {
	if (credit == null) return;
	if (ToolBox.equals(credit.getReference(), record.getField(0)) &&
			ToolBox.equals(credit.getLabel(), record.getField(1)) &&
			ToolBox.equals(credit.getAbbreviation(), record.getField(2))) return;
	credit.setReference(record.getField(0));
	credit.setLabel(record.getField(1));
	credit.setAbbreviation(record.getField(2));
	hibSession.saveOrUpdate(credit);
	ChangeLog.addChange(hibSession,
			context,
			credit,
			credit.getReference() + " " + credit.getLabel(),
			Source.SIMPLE_EDIT, 
			Operation.UPDATE,
			null,
			null);
}
 
Example 2
Source File: AccountResourceImpl.java    From authlib-agent with MIT License 6 votes vote down vote up
@Transactional
@Override
public AccountInfo updateOrCreateAccount(String id, AccountInfo info) {
	requireNonNullBody(info);

	Session session = sessionFactory.getCurrentSession();
	Account account = session.get(Account.class, id);
	if (account == null) {
		account = new Account();
		account.setId(id);
	}
	fillAccountInfo(account, info);
	session.saveOrUpdate(account);

	return new AccountInfo(account);
}
 
Example 3
Source File: MergeTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void testPersistThenMergeInSameTxnWithVersion() {
	Session s = openSession();
	Transaction tx = s.beginTransaction();
	VersionedEntity entity = new VersionedEntity( "test", "test" );
	s.persist( entity );
	s.merge( new VersionedEntity( "test", "test-2" ) );

	try {
		// control operation...
		s.saveOrUpdate( new VersionedEntity( "test", "test-3" ) );
		fail( "saveOrUpdate() should fail here" );
	}
	catch( NonUniqueObjectException expected ) {
		// expected behavior
	}

	tx.commit();
	s.close();

	cleanup();
}
 
Example 4
Source File: UserItemsDAO.java    From document-management-system with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Update user items
 */
public static void update(UserItems ui) throws DatabaseException {
	log.debug("update({})", ui);
	Session session = null;
	Transaction tx = null;

	try {
		session = HibernateUtil.getSessionFactory().openSession();
		tx = session.beginTransaction();
		session.saveOrUpdate(ui);
		HibernateUtil.commit(tx);
	} catch (HibernateException e) {
		HibernateUtil.rollback(tx);
		throw new DatabaseException(e.getMessage(), e);
	} finally {
		HibernateUtil.close(session);
	}

	log.debug("update: void");
}
 
Example 5
Source File: OfferingConsentTypes.java    From unitime with Apache License 2.0 6 votes vote down vote up
protected void update(OfferingConsentType consent, Record record, SessionContext context, Session hibSession) {
	if (consent == null) return;
	if (ToolBox.equals(consent.getReference(), record.getField(0)) &&
			ToolBox.equals(consent.getLabel(), record.getField(1)) &&
			ToolBox.equals(consent.getAbbv(), record.getField(2))) return;
	consent.setReference(record.getField(0));
	consent.setLabel(record.getField(1));
	consent.setAbbv(record.getField(2));
	hibSession.saveOrUpdate(consent);
	ChangeLog.addChange(hibSession,
			context,
			consent,
			consent.getReference() + " " + consent.getLabel(),
			Source.SIMPLE_EDIT, 
			Operation.UPDATE,
			null,
			null);
}
 
Example 6
Source File: AttachmentTypes.java    From unitime with Apache License 2.0 6 votes vote down vote up
protected void update(AttachmentType type, Record record, SessionContext context, Session hibSession) {
	if (type == null) return;
	if (ToolBox.equals(type.getReference(), record.getField(0)) &&
		ToolBox.equals(type.getAbbreviation(), record.getField(1)) &&
		ToolBox.equals(type.getLabel(), record.getField(2)) &&
		type.getVisibility() == getVisibility(record)) return;
	type.setReference(record.getField(0));
	type.setAbbreviation(record.getField(1));
	type.setLabel(record.getField(2));
	type.setVisibility(getVisibility(record));
	hibSession.saveOrUpdate(type);
	ChangeLog.addChange(hibSession,
			context,
			type,
			type.getReference(),
			Source.SIMPLE_EDIT, 
			Operation.UPDATE,
			null,
			null);
}
 
Example 7
Source File: CourseCreditFormats.java    From unitime with Apache License 2.0 6 votes vote down vote up
protected void update(CourseCreditFormat credit, Record record, SessionContext context, Session hibSession) {
	if (credit == null) return;
	if (ToolBox.equals(credit.getReference(), record.getField(0)) &&
			ToolBox.equals(credit.getLabel(), record.getField(1)) &&
			ToolBox.equals(credit.getAbbreviation(), record.getField(2))) return;
	credit.setReference(record.getField(0));
	credit.setLabel(record.getField(1));
	credit.setAbbreviation(record.getField(2));
	hibSession.saveOrUpdate(credit);
	ChangeLog.addChange(hibSession,
			context,
			credit,
			credit.getReference() + " " + credit.getLabel(),
			Source.SIMPLE_EDIT, 
			Operation.UPDATE,
			null,
			null);
}
 
Example 8
Source File: VersioningUtils.java    From modeldb with Apache License 2.0 5 votes vote down vote up
public static void saveOrUpdateArtifactPartEntity(
    ArtifactPart artifactPart, Session session, String artifactId, int artifactType) {
  ArtifactPartEntity artifactPartEntity =
      new ArtifactPartEntity(
          artifactId, artifactType, artifactPart.getPartNumber(), artifactPart.getEtag());
  session.beginTransaction();
  session.saveOrUpdate(artifactPartEntity);
  session.getTransaction().commit();
}
 
Example 9
Source File: HibernateUtil.java    From SensorWebClient with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static boolean updateUserStatus(int userID, boolean active) {
    Session session = getSessionFactory().getCurrentSession();
    session.beginTransaction();
    Criteria crit = session.createCriteria(User.class);
    List<User> users = crit.add(Restrictions.eq(ID, userID)).list();
    if (users.size() != 1) {
        return false;
    }
    User user = users.get(0);
    user.setActivated(active);
    session.saveOrUpdate(user);
    session.getTransaction().commit();
    return true;
}
 
Example 10
Source File: WarningServiceImpl.java    From fastdfs-zyc with GNU General Public License v2.0 5 votes vote down vote up
@Override
@Transactional(propagation = Propagation.REQUIRED)
public void updateWarUser(WarningUser wu) throws IOException, MyException {
    //To change body of implemented methods use File | Settings | File Templates.
    Session session = getSession();
    session.saveOrUpdate(wu);
}
 
Example 11
Source File: UserDaoImpl.java    From Resource with GNU General Public License v3.0 5 votes vote down vote up
@Override
@Transactional(propagation = Propagation.REQUIRED)
public void saveOrUpdateEntity(User user)
{
    Session session = sessionFactory.getCurrentSession();
    session.saveOrUpdate(user);
}
 
Example 12
Source File: BackrefCompositeMapKeyTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testOrphanDeleteOnSaveOrUpdateAfterSerialization() {
	Session session = openSession();
	Transaction t = session.beginTransaction();
	Product prod = new Product( "Widget" );
	Part part = new Part( "Widge", "part if a Widget" );
	MapKey mapKey = new MapKey( "Top" );
	prod.getParts().put( mapKey, part );
	Part part2 = new Part( "Get", "another part if a Widget" );
	prod.getParts().put( new MapKey( "Bottom" ), part2 );
	session.persist( prod );
	t.commit();
	session.close();

	prod.getParts().remove( mapKey );

	prod = (Product) SerializationHelper.clone( prod );

	session = openSession();
	t = session.beginTransaction();
	session.saveOrUpdate(prod);
	t.commit();
	session.close();

	session = openSession();
	t = session.beginTransaction();
	assertNull( session.get(Part.class, "Widge") );
	assertNotNull( session.get(Part.class, "Get") );
	session.delete( session.get(Product.class, "Widget") );
	t.commit();
	session.close();
}
 
Example 13
Source File: SaveOrUpdateTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testSaveOrUpdateTreeWithGeneratedId() {
	clearCounts();

	Session s = openSession();
	Transaction tx = s.beginTransaction();
	NumberedNode root = new NumberedNode( "root" );
	NumberedNode child = new NumberedNode( "child" );
	root.addChild( child );
	s.saveOrUpdate( root );
	tx.commit();
	s.close();

	assertInsertCount( 2 );
	clearCounts();

	root.setDescription( "The root node" );
	child.setDescription( "The child node" );

	NumberedNode secondChild = new NumberedNode( "second child" );

	root.addChild( secondChild );

	s = openSession();
	tx = s.beginTransaction();
	s.saveOrUpdate( root );
	tx.commit();
	s.close();

	assertInsertCount( 1 );
	assertUpdateCount( 2 );

	s = openSession();
	tx = s.beginTransaction();
	s.createQuery( "delete from NumberedNode where parent is not null" ).executeUpdate();
	s.createQuery( "delete from NumberedNode" ).executeUpdate();
	tx.commit();
	s.close();
}
 
Example 14
Source File: SaveOrUpdateTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void testSaveOrUpdateGot() {
	boolean instrumented = FieldInterceptionHelper.isInstrumented( new NumberedNode() );

	Session s = openSession();
	Transaction tx = s.beginTransaction();
	NumberedNode root = new NumberedNode( "root" );
	s.saveOrUpdate( root );
	tx.commit();
	s.close();

	assertInsertCount( 1 );
	assertUpdateCount( 0 );
	clearCounts();

	s = openSession();
	tx = s.beginTransaction();
	s.saveOrUpdate( root );
	tx.commit();
	s.close();

	assertInsertCount( 0 );
	assertUpdateCount( instrumented ? 0 : 1 );

	s = openSession();
	tx = s.beginTransaction();
	root = ( NumberedNode ) s.get( NumberedNode.class, new Long( root.getId() ) );
	Hibernate.initialize( root.getChildren() );
	tx.commit();
	s.close();

	clearCounts();

	s = openSession();
	tx = s.beginTransaction();
	NumberedNode child = new NumberedNode( "child" );
	root.addChild( child );
	s.saveOrUpdate( root );
	assertTrue( s.contains( child ) );
	tx.commit();

	assertInsertCount( 1 );
	assertUpdateCount( instrumented ? 0 : 1 );

	tx = s.beginTransaction();
	assertEquals(
			s.createCriteria( NumberedNode.class )
					.setProjection( Projections.rowCount() )
					.uniqueResult(),
	        new Integer( 2 )
	);
	s.delete( root );
	s.delete( child );
	tx.commit();
	s.close();
}
 
Example 15
Source File: RoleDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Associate a Data Set Category to the role
 *
 * @see it.eng.spagobi.commons.dao.IRoleDAO#insertRoleDataSetCategory(java.lang.Integer, java.lang.Integer)
 */
@Override
public void insertRoleDataSetCategory(Integer roleId, Integer categoryId) throws EMFUserError {
	logger.debug("IN");
	Session aSession = null;
	Transaction tx = null;
	try {
		aSession = getSession();
		tx = aSession.beginTransaction();

		SbiExtRoles hibRole = (SbiExtRoles) aSession.load(SbiExtRoles.class, roleId);

		SbiDomains category = (SbiDomains) aSession.load(SbiDomains.class, categoryId);

		Set<SbiDomains> dataSetCategories = hibRole.getSbiDataSetCategories();
		if (dataSetCategories == null) {
			dataSetCategories = new HashSet<SbiDomains>();
		}
		dataSetCategories.add(category);
		hibRole.setSbiDataSetCategories(dataSetCategories);

		aSession.saveOrUpdate(hibRole);
		aSession.flush();

		updateSbiCommonInfo4Update(hibRole);
		tx.commit();
	} catch (HibernateException he) {
		logException(he);

		if (tx != null)
			tx.rollback();

		throw new EMFUserError(EMFErrorSeverity.ERROR, 100);

	} finally {
		if (aSession != null) {
			if (aSession.isOpen()) {
				aSession.close();
				logger.debug("The [insertRoleDataSetCategory] occurs. Role cache will be cleaned.");
				this.clearCache();
			}
			logger.debug("OUT");

		}
	}

}
 
Example 16
Source File: SaveOrUpdateTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void testSaveOrUpdateDeepTreeWithGeneratedId() {
	boolean instrumented = FieldInterceptionHelper.isInstrumented( new NumberedNode() );
	clearCounts();

	Session s = openSession();
	Transaction tx = s.beginTransaction();
	NumberedNode root = new NumberedNode( "root" );
	NumberedNode child = new NumberedNode( "child" );
	NumberedNode grandchild = new NumberedNode( "grandchild" );
	root.addChild( child );
	child.addChild( grandchild );
	s.saveOrUpdate( root );
	tx.commit();
	s.close();

	assertInsertCount( 3 );
	assertUpdateCount( 0 );
	clearCounts();

	child = ( NumberedNode ) root.getChildren().iterator().next();
	grandchild = ( NumberedNode ) child.getChildren().iterator().next();
	grandchild.setDescription( "the grand child" );
	NumberedNode grandchild2 = new NumberedNode( "grandchild2" );
	child.addChild( grandchild2 );

	s = openSession();
	tx = s.beginTransaction();
	s.saveOrUpdate( root );
	tx.commit();
	s.close();

	assertInsertCount( 1 );
	assertUpdateCount( instrumented ? 1 : 3 );
	clearCounts();

	NumberedNode child2 = new NumberedNode( "child2" );
	NumberedNode grandchild3 = new NumberedNode( "grandchild3" );
	child2.addChild( grandchild3 );
	root.addChild( child2 );

	s = openSession();
	tx = s.beginTransaction();
	s.saveOrUpdate( root );
	tx.commit();
	s.close();

	assertInsertCount( 2 );
	assertUpdateCount( instrumented ? 0 : 4 );
	clearCounts();

	s = openSession();
	tx = s.beginTransaction();
	s.createQuery( "delete from NumberedNode where name like 'grand%'" ).executeUpdate();
	s.createQuery( "delete from NumberedNode where name like 'child%'" ).executeUpdate();
	s.createQuery( "delete from NumberedNode" ).executeUpdate();
	tx.commit();
	s.close();
}
 
Example 17
Source File: UserDaoImpl.java    From sdudoc with MIT License 4 votes vote down vote up
@Override
public void updateUser(User user) {
	Session session = sessionFactory.getCurrentSession();
	session.saveOrUpdate(user);
}
 
Example 18
Source File: LineageDAORdbImpl.java    From modeldb with Apache License 2.0 4 votes vote down vote up
private void saveOrUpdate(Session session, LineageEntry input, LineageEntry output) {
  session.saveOrUpdate(new LineageEntity(input, output));
}
 
Example 19
Source File: BlobDAORdbImpl.java    From modeldb with Apache License 2.0 4 votes vote down vote up
private Map.Entry<String, String> getS3PathAndMultipartUploadId(
    Session session,
    String computeSha,
    String internalVersionedPath,
    DatasetBlob.ContentCase contentCase,
    boolean partNumberSpecified,
    S3KeyFunction initializeMultipart)
    throws ModelDBException {
  UploadStatusEntity uploadStatusEntity = getUploadStatusEntity(session, computeSha, contentCase);
  String uploadId;
  if (partNumberSpecified) {
    uploadId =
        uploadStatusEntity == null
                || uploadStatusEntity.getUploadId() == null
                || uploadStatusEntity.getUploadId().isEmpty()
            ? null
            : uploadStatusEntity.getUploadId();

    String message = null;
    if (uploadId == null) {
      if (initializeMultipart == null) {
        message = "Multipart wasn't initialized";
      } else {
        uploadId = initializeMultipart.apply(internalVersionedPath).orElse(null);
        if (uploadStatusEntity == null) {
          uploadStatusEntity = new UploadStatusEntity();
        }
        uploadStatusEntity.setDataset_component_blob_id(computeSha);
        if (contentCase.equals(DatasetBlob.ContentCase.PATH)) {
          uploadStatusEntity.setComponent_blob_type(
              UploadStatusEntity.PATH_DATASET_COMPONENT_BLOB);
        } else {
          uploadStatusEntity.setComponent_blob_type(UploadStatusEntity.S3_DATASET_COMPONENT_BLOB);
        }
      }
    }
    if (message != null) {
      LOGGER.info(message);
      throw new ModelDBException(message, io.grpc.Status.Code.FAILED_PRECONDITION);
    }

    if (!Objects.equals(uploadId, uploadStatusEntity.getUploadId())
        || uploadStatusEntity.isUploadCompleted()) {
      session.beginTransaction();
      uploadStatusEntity.setUploadId(uploadId);
      uploadStatusEntity.setUploadCompleted(false);
      session.saveOrUpdate(uploadStatusEntity);
      session.getTransaction().commit();
    }
  } else {
    uploadId = null;
  }
  return new AbstractMap.SimpleEntry<>(internalVersionedPath, uploadId);
}
 
Example 20
Source File: SqlReportEntitiesPersister.java    From aw-reporting with Apache License 2.0 4 votes vote down vote up
/**
 * Persists all the given entities into the DB configured in the {@code SessionFactory}. Specify
 * the following system properties backoff.delay
 */
@Override
@Transactional
@Retryable(
    value = {LockAcquisitionException.class},
    maxAttemptsExpression = "#{ @systemProperties['retryBackoff'] ?: 20}",
    backoff =
        @Backoff(
            delayExpression = "#{ @systemProperties['retryDelay'] ?: 100}",
            maxDelayExpression = "#{ @systemProperties['retryMaxDelay'] ?: 50000 }",
            multiplierExpression = "#{ @systemProperties['retryMultiplier'] ?: 1.5}"))
public void persistReportEntities(List<? extends Report> reportEntities) {
  int batchFlush = 0;
  Session session = sessionFactory.getCurrentSession();
  FlushMode previousFlushMode = session.getHibernateFlushMode();
  session.setHibernateFlushMode(FlushMode.MANUAL);

  try {
    for (Report report : reportEntities) {
      report.setRowId();

      session.saveOrUpdate(report);
      batchFlush++;

      if (batchFlush == config.getBatchSize()) {
        session.flush();
        session.clear();
        batchFlush = 0;
      }
    }

    if (batchFlush > 0) {
      session.flush();
      session.clear();
    }
  } catch (NonUniqueObjectException ex) {
    // Github issue 268 & 280
    //   https://github.com/googleads/aw-reporting/issues/268
    //   https://github.com/googleads/aw-reporting/issues/280
    //
    // Currently we allow specifying report definitions which do not include all primary key
    // fields. This leads to cryptic hibernate errors without providing a reasonable
    // resolution strategy.
    //
    // This fix explains where to find the list of primary key fields, but does not address
    // the underlying issue of allowing non-unique rows to be downloaded in the first place.
    //
    // Ideally we would guarantee uniqueness of rows without the user having to specify the
    // PK fields.
    // However, this would be a substantial migration for the AWReporting user base.
    // Instead, we just log a (hopefully) useful error message.
    // Also note that the error message assumes that reportEntities was not empty, because
    // otherwise the exception would not have been thrown.
    logger.error(
        "Duplicate row detected. This is most likely because your report definition does not "
            + "include the primary key fields defined in {}.setRowId(). "
            + "Please add the missing fields and try again.",
        reportEntities.get(0).getClass().getName());
    throw ex;
  } finally {
    session.setHibernateFlushMode(previousFlushMode);
  }
}