Skip to content

Commit

Permalink
add named queries tutorial
Browse files Browse the repository at this point in the history
  • Loading branch information
attacomsian committed Oct 6, 2019
1 parent 13e61d0 commit 7666afc
Show file tree
Hide file tree
Showing 6 changed files with 218 additions and 7 deletions.
1 change: 1 addition & 0 deletions spring-data-jpa/jpa-queries/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@

- [Derived Query Methods in Spring Data JPA](https://attacomsian.com/blog/derived-query-methods-spring-data-jpa)
- [Spring Data JPA Custom Queries with the @Query Annotation](https://attacomsian.com/blog/spring-data-jpa-query-annotation)
- [How to Use Spring Data JPA Named Queries](https://attacomsian.com/blog/spring-data-jpa-named-queries)
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import com.attacomsian.jpa.custom.repositories.NoteRepository;
import com.attacomsian.jpa.derived.domains.User;
import com.attacomsian.jpa.derived.repositories.UserRepository;
import com.attacomsian.jpa.named.domains.Book;
import com.attacomsian.jpa.named.repositories.BookRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
Expand All @@ -14,17 +16,25 @@
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.JpaSort;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

@SpringBootApplication
public class Application {

@PersistenceContext
private EntityManager em;

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

@Bean
public CommandLineRunner runner(UserRepository userRepository, NoteRepository noteRepository) {
public CommandLineRunner runner(UserRepository userRepository,
NoteRepository noteRepository,
BookRepository bookRepository) {
return args -> {
// Like pattern
// String pattern = "%atta%@gmail%";
Expand All @@ -35,15 +45,38 @@ public CommandLineRunner runner(UserRepository userRepository, NoteRepository no
// Page<User> userPage = userRepository.findByActive(true, pageable);

// notes sorting
List<Note> startupNotes = noteRepository.findByTitle("startup", Sort.by("title").ascending());
// List<Note> startupNotes = noteRepository.findByTitle("startup", Sort.by("title").ascending());
// List<Note> techNotes = noteRepository.findByTitle("tech", Sort.by("priority").descending());
// List<Note> lengthyNotes = noteRepository.findByTitle("tech", JpaSort.unsafe("LENGTH(title)"));

List<Note> techNotes = noteRepository.findByTitle("tech", Sort.by("priority").descending());
// notes pagination
// Pageable pageable = PageRequest.of(0, 10, Sort.by("title").descending());
// Page<Note> notePage = noteRepository.findAllNotesWithPagination(pageable);

List<Note> lengthyNotes = noteRepository.findByTitle("tech", JpaSort.unsafe("LENGTH(title)"));
// create books
bookRepository.save(new Book("Java 101", "145804", 450));
bookRepository.save(new Book("Spring Bot", "48524", 289));

// notes pagination
Pageable pageable = PageRequest.of(0, 10, Sort.by("title").descending());
Page<Note> notePage = noteRepository.findAllNotesWithPagination(pageable);
// execute named queries with `EntityManager`
// Query q = em.createNamedQuery("Book.findByTitleJPQL");
// q.setParameter(1, "Java 101");
// // execute query
// List<Book> books = q.getResultList();
//
// execute native sql named query
// Query q = em.createNamedQuery("Book.findByIsbnNative");
// q.setParameter("isbn", "145804");
// // execute query
// Book book = (Book) q.getSingleResult();

// list all books
List<Book> books = bookRepository.findAllXML();

// fetch a single book
Book book = bookRepository.findByIsbnNamedFile("145804");

// multiple parameters
List<Book> moreBooks = bookRepository.findByTitleAndPagesGreaterThanJPQL("Spring Bot", 150);
};
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package com.attacomsian.jpa.named.domains;

import javax.persistence.*;
import java.util.Objects;

@Entity
@NamedQueries({
@NamedQuery(name = "Book.findAllJPQL",
query = "SELECT b FROM Book b ORDER BY b.title DESC"),
@NamedQuery(name = "Book.findByTitleJPQL",
query = "SELECT b FROM Book b WHERE b.title = ?1"),
@NamedQuery(name = "Book.findByTitleAndPagesGreaterThanJPQL",
query = "SELECT b FROM Book b WHERE b.title = :title AND b.pages > :pages")
})
@NamedNativeQueries({
@NamedNativeQuery(name = "Book.findAllNative",
query = "SELECT * FROM book b ORDER BY b.title DESC",
resultClass = Book.class),
@NamedNativeQuery(name = "Book.findByIsbnNative",
query = "SELECT * FROM book b WHERE b.isbn = :isbn",
resultClass = Book.class)
})
public class Book {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title;
@Column(unique = true)
private String isbn;
private int pages;

public Book() {
}

public Book(String title, String isbn, int pages) {
this.title = title;
this.isbn = isbn;
this.pages = pages;
}

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public String getIsbn() {
return isbn;
}

public void setIsbn(String isbn) {
this.isbn = isbn;
}

public int getPages() {
return pages;
}

public void setPages(int pages) {
this.pages = pages;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Book book = (Book) o;
return id.equals(book.id);
}

@Override
public int hashCode() {
return Objects.hash(id);
}

@Override
public String toString() {
return "Book{" +
"id=" + id +
", title='" + title + '\'' +
", isbn='" + isbn + '\'' +
", pages=" + pages +
'}';
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package com.attacomsian.jpa.named.repositories;

import com.attacomsian.jpa.named.domains.Book;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface BookRepository extends CrudRepository<Book, Long> {

// named queries declared in `jpa-named-queries.properties` file

List<Book> findAllNamedFile();

List<Book> findByTitleNamedFile(String title);

Book findByIsbnNamedFile(String isbn);

@Query(nativeQuery = true)
List<Book> findByTitleNativeNamedFile(@Param("title") String title);

// named queries declared in `orm.xml` file

List<Book> findAllXML();

List<Book> findByTitleContainingXML(String title);

@Query(nativeQuery = true)
List<Book> findByIsbnNativeXML(@Param("isbn") String isbn);

// named queries declared with `@NamedQuery`

List<Book> findAllJPQL();

List<Book> findByTitleJPQL(String title);

List<Book> findByTitleAndPagesGreaterThanJPQL(@Param("title") String title, @Param("pages") int pages);

// named queries declared with `@NamedNativeQuery`

@Query(nativeQuery = true)
List<Book> findAllNative();

@Query(nativeQuery = true)
List<Book> findByIsbnNative(@Param("isbn") String isbn);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# find all books order by title descending
Book.findAllNamedFile=SELECT b FROM Book b ORDER BY b.title DESC

# find books by title
Book.findByTitleNamedFile=SELECT b FROM Book b WHERE b.title = ?1

# find a book by isbn
Book.findByIsbnNamedFile=SELECT b FROM Book b WHERE b.isbn = ?1

# native SQL query to find books by title
Book.findByTitleNativeNamedFile=SELECT * FROM book b WHERE b.title = :title
23 changes: 23 additions & 0 deletions spring-data-jpa/jpa-queries/src/main/resources/META-INF/orm.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings version="2.0" xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm
http://java.sun.com/xml/ns/persistence/orm_2_0.xsd ">

<!--find all books order by pages descending-->
<named-query name="Book.findAllXML">
<query>SELECT b FROM Book b ORDER BY b.pages DESC</query>
</named-query>

<!--find books by title-->
<named-query name="Book.findByTitleContainingXML">
<query>SELECT b FROM Book b WHERE b.title LIKE ?1</query>
</named-query>

<!--native SQL query to find a book by isbn-->
<named-native-query name="Book.findByIsbnNativeXML"
result-class="com.attacomsian.jpa.named.domains.Book">
<query>SELECT * FROM book b WHERE b.isbn = :isbn</query>
</named-native-query>

</entity-mappings>

0 comments on commit 7666afc

Please sign in to comment.