0

I'm wondering what is the purpose of native named queries in JPA. Let's have and example:

Utility class holding native queries:

class ExampleNativeQueries {
    
    static final String NATIVE_QUERY = "select * from EXAMPLE_TABLE where EXAMPLE_VALUE = :value";
}

and Entity class + Repository:

@Entity
@Table(name = "EXAMPLE_TABLE")
public class Example {
    
    @Id
    private Long id;
    
    @Column(name = "EXAMPLE_VALUE")
    private String value;
}

interface ExampleRepository extends JpaRepository<Example, Long> {
    
    @Query(value = ExampleNativeQueries.NATIVE_QUERY, nativeQuery = true)
    List<Example> findByExampleValue(@Param("value") String value);
}

vs

@Entity
@Table(name = "EXAMPLE_TABLE")
@NamedNativeQuery(name = "Example.findByExampleValue", query = ExampleNativeQueries.NATIVE_QUERY, resultClass = Example.class)
public class Example {
    
    @Id
    private Long id;
    
    @Column(name = "EXAMPLE_VALUE")
    private String value;
}

interface ExampleRepository extends JpaRepository<Example, Long> {
    
    @Query(nativeQuery = true)
    List<Example> findByExampleValue(@Param("value") String value);
}

Is there any difference with that 2 approaches?

dev123
  • 477
  • 8
  • 20
  • My question is about somemthing else. I'm wondering what's the point of using named queries, not what they actually are. – dev123 Dec 16 '20 at 11:00
  • https://stackoverflow.com/questions/29609511/what-is-the-benefit-of-the-namedquery-annotation-in-jpa#:~:text=The%20main%20benefit%20is%20that,usage%20anywhere%20in%20the%20app. – Alan Hay Dec 16 '20 at 11:56
  • @AlanHay according to the post you linked: "The main benefit is that named queries are validated and parsed typically on application startup." - does it also concern named native queries? That example is about named JPQL query. – dev123 Dec 16 '20 at 12:01

1 Answers1

0

There is no difference in your case.

But @NamedNativeQuery can provide much more flexibility for mapping result set of native query. Look at the hibernate documentation. You can use NamedNativeQuery with ConstructorResult or for mapping joined-entities result set.

As an additional example see this.

SternK
  • 11,649
  • 22
  • 32
  • 46