2017-12-27 21 views
0

私はこれを行うにしようとしています:リポジトリの@Queryから結果を正しく変換する方法は?

@Query(value = "SELECT * from student, class where student.class = class.id ..(and more)", nativeQuery= true) 
    List<MyObject> findByStudentId(@Param("studentId") long studentId); 

これは、現在、私にこのような何かコンバータの例外をスロー:

org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.Integer] to type [com.project.model.MyObject] 
    at org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.java:324) ~[spring-core-4.3.13.RELEASE.jar:4.3.13.RELEASE] 

だから私は実装に変換が存在しなければならないと思いますが。

リストを返すと完全に機能しますが、配列としてフィールド結果を持つオブジェクトが返されます。

すべてを変更せずにクエリを使用し続けるためにこの変換を行う最良の方法は何ですか?

+0

まあ、私はあなたを考えます生徒のリストを返すことができます。次に、フィールドのサブセットでカスタムオブジェクトを作成するのではなく、生徒オブジェクトを直接使用することができます。カスタムオブジェクトを使用する理由は何ですか? – Teo

答えて

0

このシナリオでは、クエリから結果を抽出するカスタムインターフェイスを作成する必要があります。たとえば、クエリがstudent_id、class_id、student_name、student_classなどを返しているとします。必要なのは、その後、あなたのクエリが、私はカスタムクエリのこの種の選択した列名を指定することをお勧め

@Query(value = "SELECT s.student_id, c.class_id, s.student_name, s.student_class from student s, class c where student.class = class.id ..(and more)", nativeQuery= true) 
    List<MyCustomObject> findByStudentId(@Param("studentId") long studentId); 

なります

interface MyCustomObject{ 
     Long getStudentId(); 
     Long getClassId();  
     String getStudentName(); 
     String getStudentClass();    
    } 

以下のようなインターフェイスを作成することです。

0
@Query(value = "SELECT * from student, class where student.class = class.id ..(and more)", nativeQuery= true) 
    List<MyObject> findByStudentId(@Param("studentId") long studentId); 

あなたは、単に配列をオブジェクトにマッピングすることができます。サービス層で

**List<Object[]>** findByStudentId(@Param("studentId") long studentId); 

を、これは、MyObjectにのセッター要素にマッピングすることができます。

List<Object[]> listitems=repository.findByStudentId(long studentid); 
for(Object obj:listitems){ 
MyObject myobj=new MyObject(); 
System.out.println(obj[1].toString()); myobj.setid(obj[1].toString()); 
System.out.println(obj[2].toString()); 

.... 
} 
関連する問題