org.hibernate.Session#saveOrUpdate ( )源码实例Demo

下面列出了org.hibernate.Session#saveOrUpdate ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: unitime   文件: CourseCreditTypes.java
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);
}
 
源代码2 项目: authlib-agent   文件: AccountResourceImpl.java
@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);
}
 
源代码3 项目: unitime   文件: AttachmentTypes.java
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);
}
 
源代码4 项目: unitime   文件: CourseCreditFormats.java
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);
}
 
源代码5 项目: unitime   文件: OfferingConsentTypes.java
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);
}
 
源代码6 项目: document-management-system   文件: UserItemsDAO.java
/**
 * 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");
}
 
源代码7 项目: cacheonix-core   文件: MergeTest.java
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();
}
 
源代码8 项目: modeldb   文件: VersioningUtils.java
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();
}
 
源代码9 项目: cacheonix-core   文件: SaveOrUpdateTest.java
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();
}
 
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();
}
 
源代码11 项目: Resource   文件: UserDaoImpl.java
@Override
@Transactional(propagation = Propagation.REQUIRED)
public void saveOrUpdateEntity(User user)
{
    Session session = sessionFactory.getCurrentSession();
    session.saveOrUpdate(user);
}
 
源代码12 项目: fastdfs-zyc   文件: WarningServiceImpl.java
@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);
}
 
源代码13 项目: SensorWebClient   文件: HibernateUtil.java
@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;
}
 
源代码14 项目: aw-reporting   文件: SqlReportEntitiesPersister.java
/**
 * 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);
  }
}
 
源代码15 项目: sdudoc   文件: UserDaoImpl.java
@Override
public void updateUser(User user) {
	Session session = sessionFactory.getCurrentSession();
	session.saveOrUpdate(user);
}
 
源代码16 项目: cacheonix-core   文件: SaveOrUpdateTest.java
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();
}
 
源代码17 项目: Knowage-Server   文件: RoleDAOHibImpl.java
/**
 * 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");

		}
	}

}
 
源代码18 项目: cacheonix-core   文件: SaveOrUpdateTest.java
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();
}
 
源代码19 项目: modeldb   文件: LineageDAORdbImpl.java
private void saveOrUpdate(Session session, LineageEntry input, LineageEntry output) {
  session.saveOrUpdate(new LineageEntity(input, output));
}
 
源代码20 项目: modeldb   文件: BlobDAORdbImpl.java
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);
}