2014-04-27 2 views
1

다음과 같이하고 있습니다. 그것은 나를 아프게하고있다!jpa에서 엔티티를 업데이트하는 방법은 무엇입니까?

public class CounselInfoServiceImpl 
    extends BaseServiceImpl<CounselInfoDao, CounselInfoEntity, Long> 
    implements CounselInfoService { 

    @Inject 
    ClassService classService; 

    @Inject 
    @Override 
    public void setDao(CounselInfoDao dao) 
    { 
     super.setDao(dao); 
    } 

    @Override 
    public CounselInfoEntity editTo(CounselInfoEntity model) 
    { 
     CounselInfoEntity entity = id(model.getId()); 

     if (!Strings.isNullOrEmpty(model.getName())) 
     { 
      entity.setName(model.getName()); 
     } 

     if (!Strings.isNullOrEmpty(model.getAddress())) 
     { 
      entity.setAddress(model.getAddress()); 
     } 

     if (!Strings.isNullOrEmpty(model.getEducation())) 
     { 
      entity.setEducation(model.getEducation()); 
     } 

     if (!Strings.isNullOrEmpty(model.getPhone())) 
     { 
      entity.setPhone(model.getPhone()); 
     } 

     if (!Strings.isNullOrEmpty(model.getQQ())) 
     { 
      entity.setQQ(model.getQQ()); 
     } 

     if (!Strings.isNullOrEmpty(model.getRemark())) 
     { 
      entity.setPhone(model.getPhone()); 
     } 

     if (!Strings.isNullOrEmpty(model.getSchool())) 
     { 
      entity.setSchool(model.getSchool()); 
     } 

     if (model.getAge() != null) 
     { 
      entity.setAge(model.getAge()); 
     } 

     if (model.getSex() != null) 
     { 
      entity.setSex(model.getSex()); 
     } 

     if (model.getClassIntention() != null) 
     {       
      entity.setClassIntention(
         classService.id(
          model.getClassIntention().getId())); 
     } 

     return entity; 
    } 
} 

spaghetti code을 피하려면 어떤 제안을 원하십니까?

현재이 코드를 작성하는 것은 어려운 작업입니다.

편집

BTW, 나는 em.merge이 준비가 생각하지 않습니다. here

The EntityManager.merge() operation is used to merge the changes made to a detached object into the persistence context. 

참조 그것은 detached object을 언급하지만, 업데이트 모델은 최신의 조각을 얻었다. 따라서 모델을 병합하면 모델의 모든 값이 엔티티에 적용됩니다 (예 : 업데이트하지 않으려는 비밀번호).

+0

당신이 가지고있는 것은 이상한 방법입니다. 일반적으로 엔티티를 편집하기 위해 앱을 사용할 때 사용자는 엔티티의 모든 입력란을 포함하는 미리 채워진 양식을 사용하고 수정해야하는 입력란을 수정하고이 양식을 제출하면 비어 있거나 입력란이 모두 작성됩니다. 엔티티에 필드를 비워 두는 것은 "이 속성의 값을 수정하지 마십시오"라는 의미입니다. –

+0

필드를 표시하지 않기 때문에 양식에 빈 필드가 없습니다. 일부 필드는 민감합니다. 따라서 사용자는 전체 날짜의 일부만 편집 할 수 있습니다. – wener

+0

그 의미가 무엇인지 이해할 수 없습니다. 어느 날짜로 얘기하고 있니? 폼은 어떻게 생겼습니까? '민감한 부분 확인'은 무엇을 의미합니까? –

답변

0

이제 업데이트가 표시됩니다 이렇게. 그것은

  • 쉬운/필터
  • 병합하는 속성을 선택하는 것이 안전 유형의

    • 때문에 여기

      public CounselInfoEntity editTo(CounselInfoEntity model) 
      { 
          CounselInfoEntity entity = id(model.getId()); 
      
          List<? extends Attribute<CounselInfoEntity, ?>> editAttrs = Lists.<Attribute<CounselInfoEntity, ?>>newArrayList(CounselInfoEntity_.name, 
          CounselInfoEntity_.address, 
          CounselInfoEntity_.education, 
          CounselInfoEntity_.phone, 
          CounselInfoEntity_.QQ, 
          CounselInfoEntity_.remark, 
          CounselInfoEntity_.school, 
          CounselInfoEntity_.age, 
          CounselInfoEntity_.sex); 
      
          BeanHelper.merge(entity, model, BeanHelper.skipNullOrEmpty(model, editAttrs)); 
      
          if (model.getClassIntention() != null) 
          {       
           entity.setClassIntention(classService.id(model.getClassIntention().getId())); 
          } 
      
          return entity; 
      } 
      

      BeanHelper

      package me.wener.practices.web.common.util; 
      
      import com.google.common.collect.Lists; 
      import java.lang.reflect.Field; 
      import java.util.List; 
      import javax.persistence.metamodel.Attribute; 
      import lombok.extern.slf4j.Slf4j; 
      import org.apache.commons.lang3.reflect.FieldUtils; 
      
      @Slf4j 
      public class BeanHelper 
      { 
          /** 
          * 获取 bean 的属性,如果属性不存在或发生异常返回null 
          */ 
          public static Object tryGetProperty(Object bean, String attrName) 
          { 
           Object property = null; 
           try 
           { 
            Field field = FieldUtils.getField(bean.getClass(), attrName, true); 
            property = field.get(bean); 
           } catch (Exception e) 
           { 
            if (log.isErrorEnabled()) 
             log.error("Exception when get property " + attrName + " on " + bean, e); 
           } 
           return property; 
          } 
      
          public static <T, A extends Attribute<T, ?>> Object tryGetProperty(T bean, A attr) 
          { 
           return tryGetProperty(bean, attr.getName()); 
          } 
      
          public static <T, A extends Attribute<T, ?>> boolean trySetProperty(T bean, A attr, Object value) 
          { 
           return trySetProperty(bean, attr.getName(), value); 
          } 
      
          public static boolean trySetProperty(Object bean, String attrName, Object value) 
          { 
           boolean failed = false; 
           try 
           { 
            // 对于 chain 的 setter 方法, 必须要使用 force access. 
            Field field = FieldUtils.getField(bean.getClass(), attrName, true); 
            field.set(bean, value); 
           } catch (Exception e) 
           { 
            if (log.isErrorEnabled()) 
             log.error("Exception when set property " + attrName + " on " + bean, e); 
      
            failed = true; 
           } 
           return !failed; 
          } 
      
          /** 
          * Test the value of search in attrs is make the isNull and isEmpty 
          * <p/> 
          * isEmpty will apply when value is String 
          */ 
          @SafeVarargs 
          public static <E, A extends Attribute<E, ?>> List<A> skip(Object searcher, boolean skipNull, boolean skipEmpty, A... attrs) 
          { 
           return skip(searcher, skipNull, skipEmpty, Lists.newArrayList(attrs)); 
          } 
      
          public static <E, A extends Attribute<E, ?>> List<A> skip(Object searcher, boolean skipNull, boolean skipEmpty, List<A> attrs) 
          { 
           List<A> list = Lists.newArrayList(); 
           boolean valid; 
      
           for (A attr : attrs) 
           { 
            Object value = tryGetProperty(searcher, attr.getName()); 
            valid = skipNull || value != null; 
      
            if (valid && skipEmpty && value instanceof String) 
             valid = ((String) value).length() != 0; 
      
            if (valid) 
             list.add(attr); 
           } 
           return list; 
          } 
      
          @SafeVarargs 
          public static <E, A extends Attribute<E, ?>> List<A> skipNullOrEmpty(Object searcher, A... attrs) 
          { 
           return skip(searcher, true, true, attrs); 
          } 
      
          public static <E, A extends Attribute<E, ?>> List<A> skipNullOrEmpty(Object searcher, List<A> attrs) 
          { 
           return skip(searcher, true, true, attrs); 
          } 
      
          @SafeVarargs 
          public static <T, A extends Attribute<T, ?>> T merge(T target, T src, A... attrs) 
          { 
           return merge(target, src, Lists.newArrayList(attrs)); 
          } 
      
          public static <T, A extends Attribute<T, ?>> T merge(T target, T src, List<A> attrs) 
          { 
           for (A attr : attrs) 
           { 
            String attrName = attr.getName(); 
            Object value = tryGetProperty(src, attrName); 
            trySetProperty(target, attrName, value); 
           } 
      
           return target; 
          } 
      } 
      

      이 하나 더있다 inclu 드

      나는 최선을 다한다. 내가 할 수있는 최선이다.

    관련 문제