新增实体之前的处理

@param entity
@return
340178
private Entity<? extends Serializable> onBeforeSave(
			Entity<? extends Serializable> entity) {
		Class<?> cls = entity.getClass();
		String indexName = DaoHelper.getExtendFieldName(cls, ExtendField.Index);
		String pathName = DaoHelper.getExtendFieldName(cls, ExtendField.Path);
		String parentName = DaoHelper.getExtendFieldName(cls,
				ExtendField.Parent);

		// 可记录时间的
		if (Dateable.class.isAssignableFrom(cls)) {
			Date now = Calendar.getInstance().getTime();
			((Dateable) entity).setCreateDate(now);
			((Dateable) entity).setLastModifiedDate(now);
		}

		// 可树形结构化的
		if (Treeable.class.isAssignableFrom(cls)) {
			Treeable self = ((Treeable) entity);
			// 获取上级节点
			Serializable parentId = self.getParent();

			// 设置节点自身的路径
			if (isNull(parentId)) {
				self.setPath("/"); // 没有上级节点的节点
				// 设置节点自身的排位
				Object maxIndex = createCriteria(cls)
						.add(Restrictions.eq(pathName, "/"))
						.setProjection(Projections.max(indexName))
						.uniqueResult();
				self.setIndex(isNull(maxIndex) ? 1 : Integer.valueOf(maxIndex
						.toString()) + 1);
			} else {
				// 设置节点自身的排位
				Object maxIndex = createCriteria(cls)
						.add(Restrictions.eq(parentName, parentId))
						.setProjection(Projections.max(indexName))
						.uniqueResult();
				self.setIndex(isNull(maxIndex) ? 1 : Integer.valueOf(maxIndex
						.toString()) + 1);
			}
		}
		// 可移动的
		else if (Movable.class.isAssignableFrom(cls)) {
			// 设置自身的排位
			Integer maxIndex = 1;
			Object maxVal = createCriteria(cls).setProjection(
					Projections.max(indexName)).uniqueResult();
			if (notNull(maxVal)) {
				maxIndex = Integer.valueOf(maxVal.toString()) + 1;
			}
			((Movable) entity).setIndex(maxIndex);
		}

		return entity;
	}
1301490
public SqlBuilder insert(Entity entity, DialectName dialectName) {
		// 验证
		validateEntity(entity);

		if (null != wrapper) {
			// 包装表名
			// entity = wrapper.wrap(entity);
			entity.setTableName(wrapper.wrap(entity.getTableName()));
		}

		final boolean isOracle = ObjectUtil.equal(dialectName, DialectName.ORACLE);// 对Oracle的特殊处理
		final StringBuilder fieldsPart = new StringBuilder();
		final StringBuilder placeHolder = new StringBuilder();

		boolean isFirst = true;
		String field;
		Object value;
		for (Entry<String, Object> entry : entity.entrySet()) {
			field = entry.getKey();
			value = entry.getValue();
			if (StrUtil.isNotBlank(field) /* && null != value */) {
				if (isFirst) {
					isFirst = false;
				} else {
					// 非第一个参数，追加逗号
					fieldsPart.append(", ");
					placeHolder.append(", ");
				}

				this.fields.add(field);
				fieldsPart.append((null != wrapper) ? wrapper.wrap(field) : field);
				if (isOracle && value instanceof String && StrUtil.endWithIgnoreCase((String) value, ".nextval")) {
					// Oracle的特殊自增键，通过字段名.nextval获得下一个值
					placeHolder.append(value);
				} else {
					placeHolder.append("?");
					this.paramValues.add(value);
				}
			}
		}
		sql.append("INSERT INTO ")//
				.append(entity.getTableName()).append(" (").append(fieldsPart).append(") VALUES (")//
				.append(placeHolder.toString()).append(")");

		return this;
	}
1035822
public void refresh(Object entity)
    {
        if (contains(entity))
        {
            MainCache mainCache = (MainCache) getPersistenceCache().getMainCache();
            Node node = mainCache.getNodeFromCache(entity, getMetadata(entity.getClass()), this);
            // Locking as it might read from persistence context.

            try
            {
                lock.readLock().lock();
                node.setPersistenceDelegator(this);
                node.refresh();
            }
            finally
            {
                lock.readLock().unlock();
            }
        }
        else
        {
            throw new IllegalArgumentException("This is not a valid or managed entity, can't be refreshed");
        }
    }
148813
public void insert(Entity entity) {
        if (entity.getId() == null) {
            String id = dbSqlSessionFactory.getIdGenerator().getNextId();
            entity.setId(id);
        }

        Class<? extends Entity> clazz = entity.getClass();
        if (!insertedObjects.containsKey(clazz)) {
            insertedObjects.put(clazz,
                                new LinkedHashMap<String, Entity>()); // order of insert is important, hence LinkedHashMap
        }

        insertedObjects.get(clazz).put(entity.getId(),
                                       entity);
        entityCache.put(entity,
                        false); // False -> entity is inserted, so always changed
        entity.setInserted(true);
    }
9009
public void updateMappedByEntities(
      @Nonnull Entity entity, @Nullable @CheckForNull Entity existingEntity) {
    entity
        .getEntityType()
        .getMappedByAttributes()
        .forEach(
            mappedByAttr -> {
              AttributeType type = mappedByAttr.getDataType();
              if (type != ONE_TO_MANY) {
                throw new RuntimeException(
                    format(
                        "Attribute [%s] of type [%s] can't be mapped by another attribute",
                        mappedByAttr.getName(), type.toString()));
              }
              updateMappedByEntitiesOneToMany(entity, existingEntity, mappedByAttr);
            });
  }
622758
@SuppressWarnings("unchecked")
    public static <T> T copy(final T entity) {
        return copy((Class<T>) entity.getClass(), entity);
    }
1137986
public T insert(T entity) {

        if (!hasPrimaryKey(entity)) {
            throw new RuntimeException(String.format("Tried to insert entity of type %s with null or zero primary key",
                    entity.getClass().getSimpleName()));
        }

        InsertCreator insert = new InsertCreator(table);

        insert.setValue(idColumn.getColumnName(), getPrimaryKey(entity));

        if (versionColumn != null) {
            insert.setValue(versionColumn.getColumnName(), 0);
        }

        for (Column column : columns) {
            if (!column.isReadOnly()) {
                insert.setValue(column.getColumnName(), getFieldValueAsColumn(entity, column));
            }
        }

        new JdbcTemplate(ormConfig.getDataSource()).update(insert);

        if (versionColumn != null) {
            ReflectionUtils.setFieldValue(entity, versionColumn.getFieldName(), 0);
        }

        return entity;
    }
782166
@Override
    public <T> T merge(T entity)
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            Tr.debug(tc, "em.merge(" + entity + ");\n" + toString());

        return getEMInvocationInfo(true).merge(entity);
    }
98378
private T onBeforeUpdate(T entity) {
		// TODO 更新前的操作
		Class<?> cls = entity.getClass();
		String entityName = cls.getName();
		String idFieldName = getIdFieldName(cls);
		ID id = entity.getId();
		
		String indexName = DaoHelper.getExtendFieldName(cls, ExtendField.Index);
		String pathName = DaoHelper.getExtendFieldName(cls, ExtendField.Path);
		String parentName = DaoHelper.getExtendFieldName(cls, ExtendField.Parent);
		
		System.out.println(indexName + "," + pathName + "," + parentName);
		
		// 可记录时间的
		if (Dateable.class.isAssignableFrom(cls)) {
			((Dateable) entity).setLastModifiedDate(Calendar.getInstance().getTime());
		}
		
		// 可树形结构化的
		if (Treeable.class.isAssignableFrom(cls)) {
			// 判断自身位置有没有发生变化
			Treeable currObject = (Treeable) entity;
			Serializable newParentId = currObject.getParent();
			Treeable dbObject = (Treeable) getCurrentSession().get(cls, id);
			Serializable oldParentId = dbObject.getParent();
			
			System.out.println("newParentId:" + newParentId + " --> oldParentId:" + oldParentId);
			
			// 跨层级移动
			if( notNull(newParentId) && ( !newParentId.equals( oldParentId ) ) ){
				String oldPath = dbObject.getPath();
				Treeable newParent = (Treeable) getCurrentSession().get(cls, newParentId);
				String newPath =  newParent.getPath() + id.toString() + "/";
				currObject.setPath(newPath);
				
				System.out.println( "newPath:" + newPath + " --> oldPath:" + oldPath );
				
				//1.修改自身的排位
				Object maxVal = createCriteria(cls).add(Restrictions.eq(parentName, currObject.getParent())).setProjection(Projections.max(indexName)).uniqueResult();
				currObject.setIndex( isNull(maxVal) ? 1 : (Integer.valueOf(maxVal.toString()) + 1) );
				//2.如果自身的下级节点路劲：截取dbObject的path 换成	currentObject的path
				int subStart = oldPath.length() + 1;
				String hql = "update " + entityName + " set "+pathName+" = Concat(?, Substring( "+pathName+", "+subStart+", Length("+pathName+") )) where "+pathName+" like ?";
				getCurrentSession().createQuery(hql)
					.setParameter(0, newPath)
					.setParameter(1, oldPath +"_%")
					.executeUpdate();
			}
			// 同级之间移动
			else if( ! dbObject.getIndex().equals(currObject.getIndex()) ){
				// 更新目标节点的位置
				String hql = "update " + entityName + " set "+indexName+"=? where "+parentName+"=? and "+indexName+"=?";
				createQuery(hql)
					.setParameter(0, dbObject.getIndex())
					.setParameter(1, dbObject.getParent())
					.setParameter(2, currObject.getIndex())
					.executeUpdate();
			}
			
		}
		// 可移动的
		else if (Movable.class.isAssignableFrom(cls)) {
			Movable currObject = (Movable) entity;
			Movable dbObject = (Movable) getCurrentSession().get(cls, entity.getId());
			if( ! dbObject.getIndex().equals(currObject.getIndex()) ){
				String hql = "update " + entityName + " set "+indexName+"=? where "+indexName+"=? ";
				createQuery(hql)
					.setParameter(0, currObject.getIndex())
					.setParameter(1, dbObject.getIndex())
					.executeUpdate();
			}
		}
		
		return entity;
	}
600084
protected <C extends CrudResponse, T extends UpdateEntity> C handleUpdateEntity(T entity) {
        Map<String, String> uriVariables = restUriVariablesFactory.getUriVariablesForEntityUpdate(
                BullhornEntityInfo.getTypesRestEntityName(entity.getClass()), entity.getId());
        String url = restUrlFactory.assembleEntityUrlForUpdate();

        CrudResponse response;

        try {
            String jsonString = restJsonConverter.convertEntityToJsonString(entity);
            response = this.performPostRequest(url, jsonString, UpdateResponse.class, uriVariables);
        } catch (HttpStatusCodeException error) {
            response = restErrorHandler.handleHttpFourAndFiveHundredErrors(new UpdateResponse(), error, entity.getId());
        }

        return (C) response;
    }
461992
@SuppressWarnings("unchecked")
  public <E> E update(E entity) {
    try {
      entityManager.executeEntityListeners(CallbackType.PRE_UPDATE, entity);
      Intent intent = (nativeWriter instanceof Batch) ? Intent.BATCH_UPDATE : Intent.UPDATE;
      Entity nativeEntity = (Entity) Marshaller.marshal(entityManager, entity, intent);
      nativeWriter.update(nativeEntity);
      E updatedEntity = (E) Unmarshaller.unmarshal(nativeEntity, entity.getClass());
      entityManager.executeEntityListeners(CallbackType.POST_UPDATE, updatedEntity);
      return updatedEntity;
    } catch (DatastoreException exp) {
      throw DatastoreUtils.wrap(exp);
    }

  }
834704
public boolean updateEntity(Entity entity) {
        String entityName = entity.getName();
        checkEntityIsEmpty(entityName);
        QueryPart<Entity> queryPart = new Query<Entity>("entities")
                .path(entityName, true);
        return httpClientManager.updateMetaData(queryPart, patch(entity));
    }
892220
@Override
    public T create(T entity) {
        EntityManager entityManager = getEntityManager();
        entityManager.persist(entity);
        return entity;
    }
420158
public <T> T datastoreToJava(Entity entity) {
		try {
			if (entity == null) {
				return null;
			}
			T result = (T) persistentClass.newInstance();
			populate(entity, result);
			return result;
		} catch (InstantiationException e) {
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}
946367
public void update(Entity entity) {
        entityCache.put(entity,
                        false); // false -> we don't store state, meaning it will always be seen as changed
        entity.setUpdated(true);
    }
271627
public <T> void refresh(T entity) {
        DocumentInfo documentInfo = documentsByEntity.get(entity);
        if (documentInfo == null) {
            throw new IllegalStateException("Cannot refresh a transient instance");
        }

        incrementRequestCount();

        GetDocumentsCommand command = new GetDocumentsCommand(new String[]{documentInfo.getId()}, null, false);
        _requestExecutor.execute(command, sessionInfo);

        refreshInternal(entity, command, documentInfo);
    }
530434
@Override
	public void update(Object entity) {
		if (entity == null) {
			throw new IllegalArgumentException("'entity' must not be [" + entity + "]");
		}
		
		assertTransactional();
		((AppEngineGlobalTransaction) transaction.get()).coordinator().update(entity);
	}