@Query2

Yeeun·2025년 4월 24일
0

SpringBoot

목록 보기
16/46

ㅂ보드레파지토리 파일

@Query("SELECT b.seq, b.title, b.writer, b.createDate FROM Board b "
+ "WHERE b.title like %?1% ORDER BY b.seq DESC")
List<Object[]> queryAnnotationTest2(String searchKeyword);

띄어쓰기 주의

@Test
public void testQueryAnnotationTest2() {
List<Object[]> boardList = boardRepo.queryAnnotationTest2("테스트제목10");

 System.out.println("검색 결과");
	for(Object[] board:boardList) {
		System.out.println(Arrays.toString(board));
	}
 }

오브젝트리스트를 하나씩 받으면 그 안에 들어있는게 오브젝트배열이므라 , 그걸또 꺼내기위해 어레이즈를씀

📝 BoardRepository Query:

In the repository, you're using a JPQL query with a native-like syntax:

@Query("SELECT b.seq, b.title, b.writer, b.createDate FROM Board b " 
     + "WHERE b.title like %?1% ORDER BY b.seq DESC")
List<Object[]> queryAnnotationTest2(String searchKeyword);

This query:

  • Selects specific fields (seq, title, writer, createDate) from the Board entity.
  • Filters the results by the title field using a LIKE clause and the passed searchKeyword.
  • Orders the results by seq in descending order.

The result will be a list of object arrays (List<Object[]>), where each array contains the seq, title, writer, and createDate values for each Board entry.

🧐 Important Points About JPQL and Object[]:

  • Since you're only selecting specific fields from the Board entity, the query does not return a Board object but rather a raw list of data as Object[].

  • Each element in the list will be an Object[] containing the selected fields (seq, title, writer, createDate).

  • Therefore, to retrieve individual fields from each Object[], you’ll need to extract them by index from the array.


🧑‍💻 Test Case:

In your test case, you're correctly fetching the list of Object[] and printing out the results.

@Test
public void testQueryAnnotationTest2() {
    List<Object[]> boardList = boardRepo.queryAnnotationTest2("테스트제목10");
    
    System.out.println("검색 결과");
    for (Object[] board : boardList) {
        // Here, each `board` is an Object[] with the fields we selected (seq, title, writer, createDate)
        System.out.println(Arrays.toString(board));
    }
}

🔸 Explanation:

  1. boardRepo.queryAnnotationTest2("테스트제목10"): This calls your custom query method, passing in "테스트제목10" as the searchKeyword. It will return a List<Object[]>.

  2. Printing the Results:

    • Each board in the list is an Object[].
    • The Arrays.toString(board) method is used to print the contents of the Object[], which will display the seq, title, writer, and createDate fields.

    Example of a printed result for one Object[]:

    [1, "테스트 제목10", "테스터", "2025-04-24"]

    Each Object[] will contain:

    • board[0]: seq (Long)
    • board[1]: title (String)
    • board[2]: writer (String)
    • board[3]: createDate (Date)

🔸 When to Use Object[] in JPQL:

When using SELECT in JPQL to query only specific fields from an entity, you often get back an array of objects (Object[]), especially when the query is not selecting the whole entity.

Alternative: Using DTO for Better Structure (Optional)

If you want to avoid working with Object[] and prefer a more structured result, you can use a DTO (Data Transfer Object) to store the fields.

For example:

  1. Create a DTO class:

    public class BoardDTO {
        private Long seq;
        private String title;
        private String writer;
        private Date createDate;
    
        // Constructor, getters, setters, etc.
    }
  2. Modify the query to return a BoardDTO instead of an Object[]:

    @Query("SELECT new com.example.BoardDTO(b.seq, b.title, b.writer, b.createDate) "
         + "FROM Board b "
         + "WHERE b.title like %?1% "
         + "ORDER BY b.seq DESC")
    List<BoardDTO> queryAnnotationTest2(String searchKeyword);
  3. Your test would look like:

    @Test
    public void testQueryAnnotationTest2() {
        List<BoardDTO> boardList = boardRepo.queryAnnotationTest2("테스트제목10");
    
        System.out.println("검색 결과");
        for (BoardDTO board : boardList) {
            System.out.println(board.getSeq() + ", " + board.getTitle() + ", " + board.getWriter() + ", " + board.getCreateDate());
        }
    }

This approach is cleaner and allows you to work with strongly typed objects instead of Object[].


📝 Summary of Key Points:

  1. JPQL Query:

    • When selecting specific fields (like seq, title, writer, createDate), the result is returned as a List<Object[]>.
    • Each element in the list is an array of objects (Object[]) containing the selected fields.
  2. Test Case:

    • Use Arrays.toString(board) to print the Object[] for each Board.
    • You can also extract individual fields from board[0], board[1], etc., depending on the query's selected fields.
  3. DTO Approach (Optional):

    • If you want a cleaner approach, use a DTO to return the selected fields in a structured manner instead of using Object[].

0개의 댓글