practicing spring jpa @NamedQuery, @NamedNativeQuery
2015 · 10 · 081 min readPaper
Contents
In jpa.. you can query data through a repository with findAll or the findOneBy…. series,
but you can also write specific queries directly like below.
/classes/META-INF/orm.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" encoding="UTF-8"?><entity-mappingsxmlns="http://java.sun.com/xml/ns/persistence/orm"version="2.0"><named-queryname="Inter.findByAlal2"><query>select i from Inter i where i.internameko = ?1</query></named-query><named-native-queryname="Inter.findByAlal"result-class="sample.jpa.Inter"><query>select a.inter_seq, a.inter_name_ko, a.inter_name_en from tb_inter a where a.inter_name_ko = ?</query></named-native-query></entity-mappings>
Or.. you can declare it on the Entity class like below
1
2
3
4
5
6
@Entity@Table(name="tb_inter")@NamedQuery(name="User.findByAlal2",query="select i from Inter i where i.internameko = ?1")publicclassInter{....}
(@Query is a similar annotation, and it goes on the Repository.)
Difference between named-query and named-native-query
named-query runs the query against the Entity declared in the code. (see Inter.java)
named-native-query runs the query directly against the db. (so result-class must be specified.)