user9735824
user9735824

Reputation: 1256

Native Query on JPA with Random Entity class

I am trying to understand use of nativeQuery with spring data JPA. Consider following where i am pulling USER_NAME from USER table.

public interface UserRepository extends JpaRepository {

  @Query(value = "SELECT USER_NAME FROM USER WHERE EMAIL_ADDRESS = ?1", nativeQuery = true)
  String findByEmailAddress(@Param("emailAddress") String emailAddress );
}

Everything is fine. Now on same interface i can add method as below, where it is pulling from SOME_OTHER_TABLE and it will not match with entity class User.

@Query(value = "SELECT USER_NAME FROM SOME_OTHER_TABLE WHERE EMAIL_ADDRESS = ?1", nativeQuery = true)
  String findByEmailAddress(@Param("emailAddress") String emailAddress );
}

An this also works fine. Now my real question is why we need User entity class if it has nothing to do with native query. Are we just trying to make sure code will compile properly ? Also does that mean i can even put any entity class like JpaRepository<SOmeRandomEntityClass, Long> and that will still work.

Upvotes: 0

Views: 840

Answers (2)

Joost Lambregts
Joost Lambregts

Reputation: 550

Native queries are meant for the corner cases where the object oriented approach offered by jpa is not flexible enough. A native query is just a SQL query, and has no way of making use of your object structure.

To answer your question, yes you could technically add this query to any repository. Native query support in repositories is there to be able to extend your repository functionality with arbitrary SQL code.

Note that if you set native = false, you get to use jpql queries which let you use your entity structure in your queries. Note that you can omit the @query annotation entirely if you change the return type to List. Spring will implement the method automatically. (Assuming emailAddress is a property of User)

Upvotes: 1

JLazar0
JLazar0

Reputation: 1292

The use of native queries makes it unnecessary to use the entities,you could put any query that works with SqlDeveloper for example, but from my point of view this breaks with the JPA philosophy.

A robust data access framework that works independently of the DBMS.

A native would allow you, for example, to use native MySQL or Oracle functions, but when migrating from DBMS you would have to check all the native queries.

However with named queries or Criteria Builder, you will use the allowed functions or allowed methods, which will be those that you can use in all DBMS

To do this you must use Named queries or CriteriaBuilder, for what you need both entities and your metamodel

Upvotes: 1

Related Questions