Search in sources :

Example 1 with BaseDict

use of org.mx.dal.entity.BaseDict in project main by JohnPeng739.

the class ElasticAccessorRest method save.

/**
 * {@inheritDoc}
 *
 * @see ElasticAccessor#save(Base)
 */
@Override
public <T extends Base> T save(T t) throws UserInterfaceDalErrorException {
    try {
        Class<T> clazz = (Class<T>) t.getClass();
        boolean isNew;
        if (StringUtils.isBlank(t.getId())) {
            // 新数据
            t.setId(DigestUtils.uuid());
            t.setCreatedTime(System.currentTimeMillis());
            isNew = true;
        } else {
            T check = getById(t.getId(), clazz);
            if (check != null) {
                // 修改数据
                t.setCreatedTime(check.getCreatedTime());
                if (check instanceof BaseDict) {
                    ((BaseDict) t).setCode(((BaseDict) check).getCode());
                }
                isNew = false;
            } else {
                isNew = true;
            }
        }
        t.setUpdatedTime(System.currentTimeMillis());
        t.setOperator(sessionDataStore.getCurrentUserCode());
        if (isNew) {
            IndexRequest request = new IndexRequest(index, t.getClass().getName(), t.getId());
            request.source(JSON.toJSONString(t), XContentType.JSON);
            client.index(request);
        } else {
            UpdateRequest request = new UpdateRequest(index, t.getClass().getName(), t.getId());
            request.doc(JSON.toJSONString(t), XContentType.JSON);
            client.update(request);
        }
        return getById(t.getId(), (Class<T>) t.getClass());
    } catch (IOException ex) {
        if (logger.isErrorEnabled()) {
            logger.error("Save the data into elastic fail.", ex);
        }
        throw new UserInterfaceDalErrorException(UserInterfaceDalErrorException.DalErrors.DB_OPERATE_FAIL);
    }
}
Also used : BaseDict(org.mx.dal.entity.BaseDict) UpdateRequest(org.elasticsearch.action.update.UpdateRequest) UserInterfaceDalErrorException(org.mx.dal.error.UserInterfaceDalErrorException) IOException(java.io.IOException) OpenIndexRequest(org.elasticsearch.action.admin.indices.open.OpenIndexRequest) IndexRequest(org.elasticsearch.action.index.IndexRequest) CreateIndexRequest(org.elasticsearch.action.admin.indices.create.CreateIndexRequest)

Aggregations

IOException (java.io.IOException)1 CreateIndexRequest (org.elasticsearch.action.admin.indices.create.CreateIndexRequest)1 OpenIndexRequest (org.elasticsearch.action.admin.indices.open.OpenIndexRequest)1 IndexRequest (org.elasticsearch.action.index.IndexRequest)1 UpdateRequest (org.elasticsearch.action.update.UpdateRequest)1 BaseDict (org.mx.dal.entity.BaseDict)1 UserInterfaceDalErrorException (org.mx.dal.error.UserInterfaceDalErrorException)1