Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions persistence-modules/hibernate-queries-3/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>hibernate-queries-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>hibernate-queries-3</name>

<parent>
<groupId>com.baeldung</groupId>
<artifactId>persistence-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>

<dependencies>
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>jakarta.data</groupId>
<artifactId>jakarta.data-api</artifactId>
<version>${jakarta-data.version}</version>
</dependency>
<dependency>
<groupId>jakarta.annotation</groupId>
<artifactId>jakarta.annotation-api</artifactId>
<version>${jakarta-annotation.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>17</source>
<target>17</target>
<annotationProcessorPaths>
<path>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-processor</artifactId>
<version>${hibernate.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>

<properties>
<h2.version>2.1.214</h2.version>
<hibernate.version>7.4.6.Final</hibernate.version>
<jakarta-data.version>1.0.2</jakarta-data.version>
<jakarta-annotation.version>2.1.1</jakarta-annotation.version>
</properties>

</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.baeldung.hibernate.find;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

@Entity
@Table(name = "authors")
public class Author {
@Id
@Column(name = "author_id")
private Long authorId;

private String name;

public Long getAuthorId() {
return authorId;
}

public String getName() {
return name;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.baeldung.hibernate.find;

import jakarta.data.repository.Repository;
import jakarta.persistence.EntityManager;

@Repository
public interface AuthorRepository {
EntityManager entityManager();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.baeldung.hibernate.find;

import jakarta.persistence.*;

@Entity
@Table(name = "books")
public class Book {
@Id
@Column(name = "book_id")
private Long bookId;

private String title;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "author_id", nullable = false)
private Author author;
Comment on lines +7 to +16

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add a newline between fields (same elsewhere)


public Long getBookId() {
return bookId;
}

public String getTitle() {
return title;
}

public Author getAuthor() {
return author;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package com.baeldung.hibernate.find;

import java.util.List;
import java.util.Optional;

import jakarta.annotation.Nullable;
import jakarta.data.Order;
import jakarta.data.page.Page;
import jakarta.data.page.PageRequest;
import jakarta.data.repository.OrderBy;
import jakarta.data.repository.Repository;
import org.hibernate.annotations.processing.Find;

@Repository
public interface BookRepository {
@Find
@OrderBy(value = "title", descending = true)
@OrderBy("author$name")
List<Book> getAllBooks();

@Find
List<Book> getAllBooks(Order<Book> sort);

@Find
@OrderBy("title")
Page<Book> getBooksPage(PageRequest pageRequest);

@Find
Book getBookWithTitle(String title);

@Find
Optional<Book> getOptionalBookWithTitle(String title);

@Find
@Nullable
Book getNullableBookWithTitle(String title);

@Find
List<Book> getAllBooksByAuthorName(String author$name);

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
package com.baeldung.hibernate.find;

import java.util.List;
import java.util.Optional;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

import jakarta.data.Order;
import jakarta.data.Sort;
import jakarta.data.exceptions.EmptyResultException;
import jakarta.data.page.Page;
import jakarta.data.page.PageRequest;
import org.hibernate.SessionFactory;
import org.hibernate.StatelessSession;
import org.hibernate.cfg.Configuration;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

public class FindUnitTest {

private static SessionFactory sessionFactory;
private StatelessSession session;

@BeforeAll
static void createSession() {
sessionFactory = new Configuration()
.addAnnotatedClass(Author.class)
.addAnnotatedClass(Book.class)
.configure("find/hibernate.find.cfg.xml")
.buildSessionFactory();
}

@BeforeEach
void before() {
session = sessionFactory.openStatelessSession();
}

@AfterEach
void after() {
session.close();
}

@Test
void whenListingAllBooks_thenAllBooksAreReturned() {
BookRepository_ repository = new BookRepository_(session);
List<Book> books = repository.getAllBooks();

assertEquals(7, books.size());
}

@Test
void whenGettingASingleBook_thenThebookIsReturned() {
BookRepository_ repository = new BookRepository_(session);
Book book = repository.getBookWithTitle("Animal Farm");

assertEquals("Animal Farm", book.getTitle());
assertEquals(102L, book.getBookId());
}

@Test
void whenGettingAnUnknownBook_thenNothingIsReturned() {
BookRepository_ repository = new BookRepository_(session);

assertThrows(EmptyResultException.class, () -> repository.getBookWithTitle("Unknown Book"));

assertEquals(Optional.empty(), repository.getOptionalBookWithTitle("Unknown Book"));
assertNull(repository.getNullableBookWithTitle("Unknown Book"));
}

@Test
void whenListingBooksByAuthor_thenAllBooksAreReturned() {
BookRepository_ repository = new BookRepository_(session);
List<Book> books = repository.getAllBooksByAuthorName("George Orwell");

assertEquals(2, books.size());
}

@Test
void whenListingBooksInOrder_thenTheCorrectBooksAreReturned() {
BookRepository_ repository = new BookRepository_(session);
List<Book> books = repository.getAllBooks(Order.by(
Sort.asc("title"),
Sort.desc("author.name")
));

assertEquals(7, books.size());
assertEquals(101L, books.get(0).getBookId());
assertEquals(107L, books.get(6).getBookId());
}

@Test
void whenListingPagesOfBooks_thenTheCorrectBooksAreReturned() {
BookRepository_ repository = new BookRepository_(session);
Page<Book> books = repository.getBooksPage(PageRequest.ofPage(1, 3, true));

assertEquals(3, books.content().size());
assertEquals(101L, books.content().get(0).getBookId());
assertEquals(102L, books.content().get(2).getBookId());

assertEquals(7L, books.totalElements());
assertTrue(books.hasNext());
assertFalse(books.hasPrevious());
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>

<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>
<property name="connection.url">jdbc:h2:mem:find;MODE=MySQL;INIT=RUNSCRIPT FROM 'classpath:find/init.sql'</property>
<property name="hibernate.connection.driver_class">org.h2.Driver</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.hbm2ddl.auto">validate</property>
<property name="show_sql">true</property>
</session-factory>

</hibernate-configuration>
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
CREATE TABLE authors (
author_id BIGINT PRIMARY KEY,
name TEXT NOT NULL
);

CREATE TABLE books (
book_id BIGINT PRIMARY KEY,
title TEXT NOT NULL,
author_id BIGINT NOT NULL,
FOREIGN KEY (author_id) REFERENCES authors(author_id)
);

INSERT INTO authors (author_id, name) VALUES
(1, 'George Orwell'),
(2, 'Haruki Murakami'),
(3, 'Agatha Christie'),
(4, 'Ursula K. Le Guin');

INSERT INTO books (book_id, title, author_id) VALUES
(101, '1984', 1),
(102, 'Animal Farm', 1),
(103, 'Norwegian Wood', 2),
(104, 'Kafka on the Shore', 2),
(105, 'Murder on the Orient Express', 3),
(106, 'And Then There Were None', 3),
(107, 'The Left Hand of Darkness', 4);
2 changes: 2 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1693,6 +1693,7 @@
<module>spring-cloud-modules/spring-cloud-task/springcloudtaskbatch</module> <!-- JAVA-34716 -->
<module>aspectj</module> <!-- JAVA-42031 -->
<module>persistence-modules/hibernate-queries-2</module> <!-- JAVA-42042 -->
<module>persistence-modules/hibernate-queries-3</module>
<module>testing-modules/selenium-3/scrollelementintoview</module>
<module>testing-modules/selenium-3/selenium-json-demo</module>
</modules>
Expand Down Expand Up @@ -1762,6 +1763,7 @@
<module>spring-cloud-modules/spring-cloud-task/springcloudtaskbatch</module> <!-- JAVA-34716 -->
<module>aspectj</module> <!-- JAVA-42031 -->
<module>persistence-modules/hibernate-queries-2</module> <!-- JAVA-42042 -->
<module>persistence-modules/hibernate-queries-3</module>
<module>testing-modules/selenium-3/scrollelementintoview</module>
<module>testing-modules/selenium-3/selenium-json-demo</module>
<module>codenameone</module>
Expand Down