2016-07-27 2 views
0

JpaRepository를 사용하여 ID로 데이터베이스에서 객체를 가져 오려고하는데 문제가 있습니다. EmbeddedId가있는 엔티티입니다.JpaRepository가 EmbeddedID가있는 객체를 찾을 수 없습니다.

내가 개체 두 가지 방법으로 얻으려고 : SowServiceImpl

하려고 할 때 내가 얻을 예외의 방법을 사용하여 명명 된 쿼리 (findById 메소드)

  • 를 사용

    1. 을 명명 된 메서드를 사용하여 그것을 얻으십시오 :

      @Override 
      public SowDocument getById(int i) { 
          SowDocument wow = sowRepository.findById(i); 
          if (wow == null) { 
           System.out.println("NULLLLLLLLLLLLLLLL"); 
           return null; 
          } else { 
           return wow; 
          } 
      } 
      
      HTTP Status 500 - Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: Parameter with that position [1] did not exist; nested exception is java.lang.IllegalArgumentException: Parameter with that position [1] did not exist 
      ... 
      ... 
      at com.sun.proxy.$Proxy791.findById(Unknown Source) 
      at com.**.pricing.web.services.impl.SowServiceImpl.getById(SowServiceImpl.java:61) 
      at com.**.pricing.web.controllers.UserController.getSowById(UserController.java:99) 
      

      및 얻을 때 NullPointerException 나는 EmbeddedId 사용하여 점점보십시오 : 여기

      @Override 
      public SowDocument getById(int i) { 
          SowDocumentPK peek = new SowDocumentPK(); 
          peek.setId(i); 
      
          SowDocument wow = sowRepository.findOne(peek); 
          if (wow == null) { 
           System.out.println("NULLLLLLLLLLLLLLLL"); 
           return null; 
          } else { 
           return wow; 
          } 
      } 
      

      개체의 : 여기

      @Entity 
      @Table(name = "SowDocument", uniqueConstraints = { 
          @UniqueConstraint(columnNames = {"id"})}) 
      @XmlRootElement 
      @NamedQueries({ 
          @NamedQuery(name = "SowDocument.findAll", query = "SELECT s FROM SowDocument s"), 
          @NamedQuery(name = "SowDocument.findById", query = "SELECT s FROM SowDocument s WHERE s.sowDocumentPK.id = :id"), 
          @NamedQuery(name = "SowDocument.findByClientName", query = "SELECT s FROM SowDocument s WHERE s.clientName = :clientName"), 
          @NamedQuery(name = "SowDocument.findByCreationDate", query = "SELECT s FROM SowDocument s WHERE s.creationDate = :creationDate"), 
          @NamedQuery(name = "SowDocument.findByDocumentCreator", query = "SELECT s FROM SowDocument s WHERE s.sowDocumentPK.documentCreator = :documentCreator"), 
          @NamedQuery(name = "SowDocument.findBySowType", query = "SELECT s FROM SowDocument s WHERE s.sowType = :sowType")}) 
      public class SowDocument implements Serializable { 
      
          private static final long serialVersionUID = 1L; 
          @EmbeddedId 
          protected SowDocumentPK sowDocumentPK; 
          @Size(max = 50) 
          @Column(name = "clientName", length = 50) 
          private String clientName; 
          @Size(max = 45) 
          @Column(name = "creationDate", length = 45) 
          private String creationDate; 
          @Lob 
          @Column(name = "data") 
          private byte[] data; 
          @Size(max = 45) 
          @Column(name = "sowType", length = 45) 
          private String sowType; 
          @JoinColumn(name = "documentCreator", referencedColumnName = "id", nullable = false, insertable = false, updatable = false) 
          @ManyToOne(optional = false) 
          private User user; 
      
          public SowDocument() { 
          } 
      
          public SowDocument(SowDocumentPK sowDocumentPK) { 
           this.sowDocumentPK = sowDocumentPK; 
          } 
      
          public SowDocument(int id, int documentCreator) { 
           this.sowDocumentPK = new SowDocumentPK(id, documentCreator); 
          } 
      
          public SowDocumentPK getSowDocumentPK() { 
           return sowDocumentPK; 
          } 
      
          public void setSowDocumentPK(SowDocumentPK sowDocumentPK) { 
           this.sowDocumentPK = sowDocumentPK; 
          } 
      
          public String getClientName() { 
           return clientName; 
          } 
      
          public void setClientName(String clientName) { 
           this.clientName = clientName; 
          } 
      
          public String getCreationDate() { 
           return creationDate; 
          } 
      
          public void setCreationDate(String creationDate) { 
           this.creationDate = creationDate; 
          } 
      
          public byte[] getData() { 
           return data; 
          } 
      
          public void setData(byte[] data) { 
           this.data = data; 
          } 
      
          public String getSowType() { 
           return sowType; 
          } 
      
          public void setSowType(String sowType) { 
           this.sowType = sowType; 
          } 
      
          public User getUser() { 
           return user; 
          } 
      
          public void setUser(User user) { 
           this.user = user; 
          } 
      
          @Override 
          public int hashCode() { 
           int hash = 0; 
           hash += (sowDocumentPK != null ? sowDocumentPK.hashCode() : 0); 
           return hash; 
          } 
      
          @Override 
          public boolean equals(Object object) { 
           // TODO: Warning - this method won't work in the case the id fields are not set 
           if (!(object instanceof SowDocument)) { 
            return false; 
           } 
           SowDocument other = (SowDocument) object; 
           if ((this.sowDocumentPK == null && other.sowDocumentPK != null) || (this.sowDocumentPK != null && !this.sowDocumentPK.equals(other.sowDocumentPK))) { 
            return false; 
           } 
           return true; 
          } 
      
      
      } 
      

      그리고 자사의 임베디드 ID : 여기

      @Embeddable 
      public class SowDocumentPK implements Serializable { 
      
          @Basic(optional = false) 
          @Column(name = "id", nullable = false) 
          private int id; 
          @Basic(optional = false) 
          @NotNull 
          @Column(name = "documentCreator", nullable = false) 
          private int documentCreator; 
      
          public SowDocumentPK() { 
          } 
      
          public SowDocumentPK(int id, int documentCreator) { 
           this.id = id; 
           this.documentCreator = documentCreator; 
          } 
      
          public int getId() { 
           return id; 
          } 
      
          public void setId(int id) { 
           this.id = id; 
          } 
      
          public int getDocumentCreator() { 
           return documentCreator; 
          } 
      
          public void setDocumentCreator(int documentCreator) { 
           this.documentCreator = documentCreator; 
          } 
      
          @Override 
          public int hashCode() { 
           int hash = 0; 
           hash += (int) id; 
           hash += (int) documentCreator; 
           return hash; 
          } 
      
          @Override 
          public boolean equals(Object object) { 
           // TODO: Warning - this method won't work in the case the id fields are not set 
           if (!(object instanceof SowDocumentPK)) { 
            return false; 
           } 
           SowDocumentPK other = (SowDocumentPK) object; 
           if (this.id != other.id) { 
            return false; 
           } 
           return this.documentCreator == other.documentCreator; 
          } 
      
      
      } 
      

      을 년대 SowRepository에 대한 코드 :

      public interface SowRepository extends JpaRepository<SowDocument, Serializable> { 
      
          SowDocument findById(int i); 
      
      } 
      

      다음은 SowService에 대한 코드 :

      @Service 
      public class SowServiceImpl implements SowService { 
      
          @Autowired 
          private SowRepository sowRepository; 
      
          @Override 
          public void save(SowDocument sow) { 
           sowRepository.save(sow); 
          } 
      
          @Override 
          public Collection<SowDocument> getAll() { 
           return sowRepository.findAll(); 
          } 
      
          @Override 
          public SowDocument getById(int i) { 
           SowDocumentPK peek = new SowDocumentPK(); 
           peek.setId(i); 
           return sowRepository.findOne(i); 
          } 
      
      
      } 
      

      내 생각은 어떻게 든 SowDocument/SowDocumentPK 또는 JpaRepository을 사용하는 방법을 잘못-이해시 사이에 잘못 매핑 (들)을 가지고있다.

  • +0

    'ShowDocumentPK'에는 2 개의 필드가 있지만'SowDocumentPK peek = new SowDocumentPK(); peek.setId (i);'를 호출하고 기본 키로 전달합니다. 그것은 신중한가요? – ujulu

    +0

    전체 합성이 아닌 자체 ID로 개체를 가져 오려면 BOTH 필드를 지정해야합니까? – Zeratas

    +0

    아래 답변에서 어떻게 사용하는지 설명하려고했습니다. 그것이 당신을 돕는 지보십시오. 그렇지 않으면 나에게 의견을 남겨주세요. – ujulu

    답변

    1

    SpringData JPA를 사용하고있는 것 같습니다. 이 정확하면, JpaRepostory 인터페이스의 슈퍼 타입 인 CrudRepository 정의하는 방법을 찾습니다

    public interface CrudRepository<T, ID extends Serializable> extends Repository<T, ID> { 
        ... 
        T findOne(ID id); 
        ... 
    } 
    

    그리고 (BTW 너무 구현을 게시해야한다) 당신이이 인터페이스를 확장하고 있습니다 :

    public interface SowRepository extends JpaRepository<SowDocument, Serializable> { 
        SowDocument findById(int i); 
    } 
    

    findById(int i) 메서드는 에 정의되어 있습니다. JpaRepository 유형 계층 구조의 인터페이스 중은 사용자가 직접 확장 한 것을 의미합니다.

    한편 ID 유형이 int 인 엔티티가 없습니다. 엔티티의 ID 유형은 두 필드로 구성된 ShowDocumentPK 유형으로 정의됩니다. (또는 JpaRepository의 공식 구현 클래스를 사용 즉, SimpleJpaRepository)

    public interface SowRepository extends JpaRepository<SowDocument, ShowDocumentPK> { 
        SowDocument findById(ShowDocumentPK id); 
    } 
    

    을 그리고 스스로 방법 findById()을 구현 :

    그래서 저장소의 정의는 다음과 같이한다.

    그리고 당신이 ShowDocumentPK의 인스턴스를 생성하고 예를 들어, findById() 방법에 전달해야합니다

    결론적으로
    SowDocumentPK peek = new SowDocumentPK(); 
    peek.setId(1); 
    peek.setDocumentCreator(100); 
    
    SowDocument wow = sowRepository.findById(peek); 
    

    : 귀하의 ID 유형 intfindById(int)이 아닌 어떻게 구현하는 방법이 아니다 당신의 경우에.

    호프를 올바르게 구현하는 방법을 알려주세요.

    +0

    나는 findById를 실제로 혼자서했다. 나는 CRUDRepository를 들여다 보았습니다. 당신이 말하기 전에 말했듯이, 나 자신도 같은 결론을 내었습니다. NamedQuery를 사용하여 지금 작업 할 수있었습니다. – Zeratas

    관련 문제