Native Queries
Plain SQL.
Sometimes you need real SQL. A database feature that JPQL doesn't have, or a report with grouping. Native queries let you write plain SQL.
- Real SQL
- Database features
- Reports
Native SQL
Native query equals true means, this is plain SQL, using the table name, book. The second query groups books by author, using a Java text block. Its results go into Author Stats, an interface, with one getter per column. Spring Data fills it in for us. This is called a projection.
public interface BookRepository extends JpaRepository<Book, Long> {
@Query(value = "SELECT * FROM book WHERE LOWER(title) LIKE '%dune%'",
nativeQuery = true)
List<Book> duneBooks();
@Query(value = """
SELECT author, COUNT(*) AS books, MIN(price) AS cheapest
FROM book GROUP BY author ORDER BY books DESC, author""", nativeQuery = true)
List<AuthorStats> authorStats();
interface AuthorStats {
String getAuthor();
long getBooks();
double getCheapest();
}
}A small report
The runner prints the dune books, then one line per author. Run it. Both Dune books are found. Then each author, with their number of books, and their cheapest price.
@Component
public class QueryDemo implements CommandLineRunner {
private final BookRepository books;
public QueryDemo(BookRepository books) { this.books = books; }
@Override
public void run(String... args) {
System.out.println(books.duneBooks());
books.authorStats().forEach(s -> System.out.println(
s.getAuthor() + ": " + s.getBooks() + " books, from " + s.getCheapest()));
}
}[Book 1: Dune (9.99), Book 4: Children of Dune (8.49)] Frank Herbert: 2 books, from 8.49 J.R.R. Tolkien: 2 books, from 8.99 Jane Austen: 2 books, from 6.99 Madeline Miller: 2 books, from 9.49
Also uses Book.java
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String author;
private double price;
protected Book() {}
public Book(String title, String author, double price) {
this.title = title; this.author = author; this.price = price;
}
public Long getId() { return id; }
public String getTitle() { return title; }
public String getAuthor() { return author; }
public double getPrice() { return price; }
public void setPrice(double price) { this.price = price; }
@Override
public String toString() { return "Book " + id + ": " + title + " (" + price + ")"; }
}Also uses BookRepository.java
public interface BookRepository extends JpaRepository<Book, Long> {
@Query(value = "SELECT * FROM book WHERE LOWER(title) LIKE '%dune%'",
nativeQuery = true)
List<Book> duneBooks();
@Query(value = """
SELECT author, COUNT(*) AS books, MIN(price) AS cheapest
FROM book GROUP BY author ORDER BY books DESC, author""", nativeQuery = true)
List<AuthorStats> authorStats();
interface AuthorStats {
String getAuthor();
long getBooks();
double getCheapest();
}
}Also uses data.sql
INSERT INTO book (title, author, price) VALUES
('Dune', 'Frank Herbert', 9.99),
('The Hobbit', 'J.R.R. Tolkien', 8.99),
('Circe', 'Madeline Miller', 10.99),
('Children of Dune', 'Frank Herbert', 8.49),
('Song of Achilles', 'Madeline Miller', 9.49),
('The Fellowship of the Ring', 'J.R.R. Tolkien', 11.99),
('Emma', 'Jane Austen', 6.99),
('Persuasion', 'Jane Austen', 7.49);Also uses application.properties
spring.jpa.defer-datasource-initialization=trueJPQL or native?
Prefer derived methods, and JPQL, because they work on any database. Use native SQL only when you need a special database feature. And remember, native queries use table and column names.
| key | value |
|---|---|
| First choice | derived methods |
| Then | JPQL @Query |
| Last | native SQL |
| Native uses | tables + columns |
Summary
Native queries run plain SQL. Interface projections give you just the columns you need. Next, counting, and exists.
Key takeaways- nativeQuery = true
- Interface projections
- Prefer JPQL