当仅修改实体obj的几个字段并且其余字段不应为空时,如何更新Hibernate实体记录

时间:2017-07-03 07:15:05

标签: java hibernate

此代码是否有任何其他不同的解决方案。 对于每个pojo类,我们必须检查来自浏览器的修改数据,我们只将修改后的数据存储到数据库中。

见下面的billingTax obj来自浏览器,它是更新的数据 并且从数据库中检索billingtaxDbObject obj,我们将检查条件是否更新了更新数据

如果pojo类有20个字段,我们必须在条件下写20 如果pojo类有5个字段,我们必须在条件

时写5 如果修改数据的条件被修改,或者还有其他最简单的方法,那么

而不是写作?

@Override

    public BillingTax update(BillingTax billingTax) throws DataInsufficientException, RecordNotFoundException {
        log.debug("BillingTaxServiceImpl.update()....................");
    try {

        if (billingTax == null)
            throw new DataInsufficientException("billingTax object is null");

        BillingTax billingtaxDbObject = get(billingTax.getId());

        if (billingtaxDbObject == null)
            throw new RecordNotFoundException("billingTax object is not found in database");

        if (billingTax.getTaxApplyType() != null
                && !billingTax.getTaxApplyType().equals(billingtaxDbObject.getTaxApplyType()))
            billingtaxDbObject.setTaxApplyType(billingTax.getTaxApplyType());

        if (billingTax.getCode() != null && !billingTax.getCode().trim().equalsIgnoreCase("null")
                && !billingTax.getCode().equalsIgnoreCase(billingtaxDbObject.getCode()))
            billingtaxDbObject.setCode(billingTax.getCode());

        if (billingTax.getName() != null && !billingTax.getName().trim().equalsIgnoreCase("null")
                && !billingTax.getName().equalsIgnoreCase(billingtaxDbObject.getName()))
            billingtaxDbObject.setName(billingTax.getName());

        if (billingTax.getDescription() != null && !billingTax.getDescription().trim().equalsIgnoreCase("null")
                && !billingTax.getDescription().equalsIgnoreCase(billingtaxDbObject.getDescription()))
            billingtaxDbObject.setDescription(billingTax.getDescription());

        if (billingTax.getServiceTypeForTax() != null
                && !billingTax.getServiceTypeForTax().equals(billingtaxDbObject.getServiceTypeForTax()))
            billingtaxDbObject.setServiceTypeForTax(billingTax.getServiceTypeForTax());

        if (billingTax.getTaxValue() != null && !billingTax.getTaxValue().equals("null")
                && !billingTax.getTaxValue().equals(billingtaxDbObject.getTaxValue()))
            billingtaxDbObject.setTaxValue(billingTax.getTaxValue());

        if (billingTax.getStatus() != null && !billingTax.getStatus().equals(billingtaxDbObject.getStatus()))
            billingtaxDbObject.setStatus(billingTax.getStatus());

        if (billingTax.getOrderNo() != null && !billingTax.getOrderNo().equals("null")
                && !billingTax.getOrderNo().equals(billingtaxDbObject.getOrderNo()))
            billingtaxDbObject.setOrderNo(billingTax.getOrderNo());

        if (billingTax.getId() != null && !billingTax.getId().trim().equalsIgnoreCase(billingtaxDbObject.getId())
                && !billingTax.getId().equalsIgnoreCase(billingtaxDbObject.getId()))
            billingtaxDbObject.setId(billingTax.getId());

        if (billingTax.getStartDate()!= null && !billingTax.getStartDate().equals(billingtaxDbObject.getStartDate()))
            billingtaxDbObject.setStartDate(billingTax.getStartDate());

        if (billingTax.getEndDate()!= null && !billingTax.getEndDate().equals(billingtaxDbObject.getEndDate()))
            billingtaxDbObject.setEndDate(billingTax.getEndDate());

        billingtaxDbObject.setUpdatedDate(new Date());
        return billingTaxDAO.update(billingtaxDbObject);

    } catch (Exception e) {
        log.error("BillingTaxServiceImpl.update()....................exception:" + e.getMessage());
        throw e;
    }
}

3 个答案:

答案 0 :(得分:1)

如果您可以避免检查dto和实体之间的更改并更新来自Web的所有字段,则可以使用hibernate的动态更新来执行此操作。如果你需要从web和实体检查dto,你可以使用apache bean util来查找所有更改的值(或者如果你有java的反射,则使用spring util ...)并使用动态更新进行更新。

请参阅:BeanUtils

BeanUtils.copyProperties()//有3种方法。

检查它在源代码中的工作原理。 创建自己的util方法,类似于BeanUtils.copyProperties(),但是需要使用逻辑(非null并且不等于source-entity值)。

还使用BeanUtils中的方法来获取PropertyDescriptor:

  

public static PropertyDescriptor [] getPropertyDescriptors(Class clazz)                                                      抛出BeansException

遍历PropertyDescriptor数组并检查您是否需要(使用ReflectionUtils将值设置为源。)

使用这种方法,您只填充非空的属性并更改(如果需要)到billingtaxDbObject并更新它。

您可以将您的复制/合并方法放入某个util类中,并将其重新用于需要从dto复制到实体并进行一些检查的所有位置。

答案 1 :(得分:0)

这是通过从pojo类获取所有字段/属性并使用wheter null数据或修改数据进行检查来开发的。 下面是代码:

copyProperties(billingTax,billingtaxDbObject);

public void copyProperties(BillingTax source,BillingTax dest)抛出异常{

    if (source == null)
        throw new DataInsufficientException("billingTax object is null");

    if (dest == null)
        throw new RecordNotFoundException("billingtaxDbObject object is not found in database");

    try{
        for (Field field : source.getClass().getDeclaredFields()) {

            field.setAccessible(true);
            Object sourceValue = field.get(source);
            Object destValue=field.get(dest);

            if(sourceValue!=null && sourceValue!="" && sourceValue!="null"){

                if(sourceValue instanceof String){
                    if(!sourceValue.toString().trim().equalsIgnoreCase("null")){
                        if(!sourceValue.toString().equalsIgnoreCase(destValue.toString())){
                            field.set(dest, sourceValue);
                            System.err.println(field.getName()+" is modified:"+field.get(dest));
                        }
                    }
                }
                else{
                    if(!sourceValue.equals("null") && !sourceValue.equals(destValue)){
                        field.set(dest, sourceValue);
                        System.err.println(field.getName()+" is modified:"+field.get(dest));
                    }
                }
            }
        }
        System.out.println();
    }catch (Exception e) {
         throw e;
    }
}

答案 2 :(得分:0)

public class CopyConverter<T> {

    private List<String> errorMessages = new ArrayList<>();
    private int countSuccess = 0;

    public  CopyConverter<T> convert(T source, T target, Set<String> ignoreFields){
        copyProperties(source,target,ignoreFields);
        return this;
    }

    public boolean hasError(){
        return errorMessages.isEmpty();
    }

    public List<String> getErrorMessages(){
        return errorMessages;
    }

    private boolean copyProperties(T source ,T target , Set<String> ignoreFields) {

        Objects.requireNonNull(source , "..error message...");
        Objects.requireNonNull(target , "..error message...");

        try {
            Map<String, Field> fieldNameMapping = buildFiledMap(target.getClass().
                                                       getDeclaredFields());
            ignoreFields = (ignoreFields == null ? new HashSet<>() : ignoreFields);


            for (Map.Entry<String, Field> fieldEntry : fieldNameMapping.entrySet()) {
                if (ignoreFields.contains(fieldEntry.getKey())) {
                    continue;
                }
                Field field = fieldEntry.getValue();
                field.setAccessible(true);
                Object sourceValue = field.get(source);
                Object targetValue = field.get(source);

                if (isChangedAsString(sourceValue, targetValue)) {
                    field.set(target, sourceValue);
                    continue;
                }
                if (isChangedAsObject(sourceValue, targetValue)) {
                    field.set(target, sourceValue);
                }
                countSuccess++;
            }
        } catch (Exception e) {
            errorMessages.add(".......");
            log.info(....);
        }
        return countSuccess == 0;
    }

    private Map<String, Field> buildFiledMap(Field[] fields) {
        Map<String, Field> fieldMap = new HashMap<>(fields.length);
        //Stream.of(fields).collect(Collectors.toMap())
        for (Field field : fields) {
            fieldMap.put(field.getName(), field);
        }
        return fieldMap;
    }

    private boolean isChangedAsObject(Object obj1, Object obj2) {
        return (obj1 == null && obj2 != null) || (obj1 != null && !obj1.equals(obj1));
    }


    private boolean isChangedAsString(Object obj1, Object obj2) {
        if (obj1 instanceof String && obj2 instanceof String) {
            String value1 = (String) obj1;
            String value2 = (String) obj2;
            return value1 != null &&
                    !value1.trim().equalsIgnoreCase("null") &&//strange check
                    !value1.equalsIgnoreCase(value2);
        }
        return false;
    }
}