@Query

Yeeun·2025년 4월 24일
0

SpringBoot

목록 보기
15/46

로딩시점 파싱, 컴파일시점에 오류못잡음 /따라서 한줄씩 테스트해가며 완성해야함.

네이티브쿼리는 똑같이 쿼리스트링을 씀. 일반적쿼리랑 같음. ||이건 스트링 붙이는 h2에서 쓰는 연산자 . 오라클,마이에스큐엘 등 랭귀지에따라 다름. 특정클래스 데이터타입이 아니라 알수없는 데이터타입의 배열형태로 넘어가기에 특정필드만 조회는것과 똑같이 리스트 오브젝트로 받아야함. 클래스 탕비을 그렇게해야함.
entitymanager factory 오류메세지 이런거면 레파지토리 인터페이스에 정의해둔 메소드가 잘못된것임. 쿼리문중ㅇ에 문제가 있던, 메소드에 문제가 있던. jpa 장점은 소스코드를 자동으로 만들어주는게 최고의 장점인데 (인터페이스만 정의하면 자동으로 소스코드를 만들어서 클래스로 만들어 자동으로 빈으로 올려주는게 jpa의 역할. 인터페이스를 클래스로 만들어야하는데 만들때오류가 나면 빈객체에 못올리니 오류가 나기에 나는 오류메세지임.

entitymanagerfactory 뜨면 무조건 레파지토리 파일가서 확인하기 .

🔸 로딩 시점 파싱 / 컴파일 시점에 오류를 못 잡음

In JPA (and especially with Spring Data JPA), the actual SQL query and its execution logic are resolved at runtime rather than compile-time. This is different from standard SQL queries or queries in languages that compile and check syntax errors before execution.

  • Compile-time errors (like syntax errors in SQL or Java code) can be caught by the compiler.
  • However, runtime errors (like incorrect query structure or invalid parameters) are only caught when the code runs, which is why debugging and testing in smaller chunks is essential.

🧑‍💻 테스트해가며 완성해야 함

Because of this runtime-based behavior, it's crucial to test queries step by step, particularly when you're writing complex or dynamic queries.

  • Unit tests or integration tests (e.g., using @SpringBootTest) help ensure that each part of the logic is functioning as expected before integrating it into the larger codebase.
  • Log output or debugging tools can help when queries are not returning expected results.

🔸 네이티브 쿼리 사용 시, 일반적인 쿼리 문자열

When you're using native queries, the format is indeed similar to how you would write SQL in any database.

Example of Native Query:

@Query(value = "SELECT * FROM board WHERE title LIKE %?1%", nativeQuery = true)
List<Object[]> searchByTitle(String titleKeyword);
  • The syntax used here is pure SQL, and you can write it just like you would in any SQL environment, like Oracle, MySQL, etc.
  • The key difference is the nativeQuery = true flag, which tells Spring Data JPA to execute the query as a native SQL query rather than JPQL.

🔸 || 연산자 (문자열 결합)

In H2, Oracle, MySQL, and other databases, string concatenation may differ slightly. You are right in noting that the concatenation operator is different between database types.

  • H2: || is used to concatenate strings.
  • MySQL/Oracle: You might need to use CONCAT() to concatenate strings instead of ||.

Example of Concatenation in H2:

SELECT * FROM board WHERE title LIKE '%' || ?1 || '%'

In MySQL or Oracle, you might do:

SELECT * FROM board WHERE title LIKE CONCAT('%', ?1, '%')

This difference is important because if you’re moving between databases or testing in different environments, you should ensure you're using the right operator for string concatenation.


🔸 리스트로 받아야 하는 이유

When using native queries, especially when selecting partial data (not a full entity), the result is typically returned as a list of Object[] or a list of Map<String, Object>. This is because the query doesn't directly map to an entity but rather to individual fields.

Example:

@Query(value = "SELECT title, writer FROM board WHERE title LIKE %?1%", nativeQuery = true)
List<Object[]> searchByTitle(String titleKeyword);
  • Here, each element in the list will be an Object[] with two elements (title and writer).
  • This is different from JPA, where the result is directly mapped to an entity object.

If you want to fetch specific fields but also want a more structured result, you might use a DTO (Data Transfer Object) to wrap the fields.


🔸 EntityManagerFactory 오류 메시지

EntityManagerFactory errors typically arise due to issues in your repository interface or when the JPA provider cannot create the necessary database connections or entities.

When you see errors related to EntityManagerFactory, it usually means:

  1. Repository Method Issue: The method you defined in your repository interface might have a problem. For example, if you're trying to run a query that isn't properly formatted or mapped to an entity.

    • Double-check your query method signature and the JPQL or native SQL query to make sure it’s valid.
  2. Incorrect Entity Configuration: If the entity class or the mapping between the repository and the entity is incorrect, this could prevent Spring from properly wiring everything up.

  3. Missing Entity: If your entity class is not properly annotated or there's an issue in its configuration (e.g., not properly scanned by Spring Boot), it might prevent the EntityManagerFactory from being created.


🧑‍💻 Troubleshooting: EntityManagerFactory 오류

  1. Check the Repository: Go to the repository interface and ensure your method signatures are correct.

    • Is the query formatted correctly?
    • Does the method name match the query's expected results?
  2. Check Your Entity Class: Ensure that all the fields in the Board entity match the database schema and that the class is properly annotated with @Entity.

  3. Verify the Configuration: Check the configuration files for the data source and JPA setup to make sure Spring is properly connecting to the database.

  4. Look at the Stack Trace: The error message often gives clues about which part of the configuration or code is failing.


🔸 @Query 메소드에서 발생할 수 있는 오류

  • If the query is incorrect or mismatched with the method signature, it will cause runtime errors when Spring tries to create the EntityManagerFactory.
  • You can also see errors like "Unknown property" if the method is referring to a field that doesn't exist in the entity.

📝 Summary

  1. Native queries are just plain SQL and behave similarly to what you’d write in an SQL database, except they require the nativeQuery = true flag.
  2. String concatenation differs between databases, so make sure to use the correct operator for your database (e.g., || for H2, CONCAT() for MySQL/Oracle).
  3. Repository errors related to EntityManagerFactory typically point to issues with how the repository is defined or how the entity is mapped.
  4. Debugging tip: Always go back to the repository and query method to verify the correctness of the logic.

If you're still seeing issues, feel free to share any error messages or stack traces you’re encountering, and I can help you debug more specifically! 😊

0개의 댓글