Add native jpa sample.

See #654
This commit is contained in:
Christoph Strobl
2022-10-12 10:38:27 +02:00
committed by Mark Paluch
parent d172c56dde
commit 5af0cb7983
11 changed files with 463 additions and 0 deletions

View File

@@ -0,0 +1,48 @@
== Spring Data Jpa - GraalVM native image
This example compiles a basic Spring Data Jpa application into a GraalVM native image.
=== Install GraalVM & native image tooling
Download and install GraalVM using https://sdkman.io/[SDKMAN!].
```
$> sdk install java <recent version>.r17-grl
$> gu install native-image
```
=== Compile to native image
The maven build uses a dedicated profile `native` to trigger the native image creation.
```
$> maven clean package -P native
```
This will create the native executable in the target folder.
=== Run the image
Run the image directly from your console as shown below.
This will print results of crud functions invoked via a `CommandLineRunner`.
```
$> ./target/spring-data-jpa-graalvm-native
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v3.0.0-SNAPSHOT)
INFO 82562 --- [ main] e.s.j.g.GraalvmNativeApplication : Starting GraalvmNativeApplication using Java 17.0.4 with PID 51404
INFO 51404 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
INFO 51404 --- [ main] c.example.data.jpa.DataJpaApplication : Started DataJpaApplication in 0.079 seconds (process running for 0.097)
insertAuthors(): author1 = Author{name='Josh Long'}
insertAuthors(): author2 = Author{name='Martin Kleppmann'}
listAllAuthors(): author = Author{name='Josh Long'}
Book{title='Reactive Spring'}
...
```

View File

@@ -0,0 +1,65 @@
<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 https://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-data-jpa-graalvm-native</artifactId>
<parent>
<groupId>org.springframework.data.examples</groupId>
<artifactId>spring-data-examples</artifactId>
<version>2.0.0.BUILD-SNAPSHOT</version>
</parent>
<name>Spring Data JPA - GraalVM Native Image</name>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>jakarta.persistence</groupId>
<artifactId>jakarta.persistence-api</artifactId>
<version>3.0.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.hibernate.orm.tooling</groupId>
<artifactId>hibernate-enhance-maven-plugin</artifactId>
<version>6.1.4.Final</version>
<executions>
<execution>
<configuration>
<enableLazyInitialization>true</enableLazyInitialization>
<enableDirtyTracking>true</enableDirtyTracking>
<enableAssociationManagement>true</enableAssociationManagement>
</configuration>
<goals>
<goal>enhance</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,32 @@
/*
* Copyright 2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.data.jpa;
import java.util.Optional;
import com.example.data.jpa.model.Author;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.ListCrudRepository;
public interface AuthorRepository extends ListCrudRepository<Author, Long> {
Optional<Author> findByNameContainingIgnoreCase(String partialName);
@Query("SELECT a FROM Author a WHERE a.name = :name")
Optional<Author> queryFindByName(String name);
}

View File

@@ -0,0 +1,101 @@
/*
* Copyright 2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.data.jpa;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import com.example.data.jpa.model.Author;
import com.example.data.jpa.model.Book;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@Component
class CLR implements CommandLineRunner {
private final AuthorRepository authorRepository;
CLR(AuthorRepository authorRepository) {
this.authorRepository = authorRepository;
}
@Override
@Transactional
public void run(String... args) {
var authors = insertAuthors();
listAllAuthors();
findById(authors);
findByPartialName();
queryFindByName();
deleteAll();
}
private void deleteAll() {
this.authorRepository.deleteAll();
long count = this.authorRepository.count();
System.out.printf("deleteAll(): count = %d%n", count);
}
private void queryFindByName() {
Author author1 = this.authorRepository.queryFindByName("Josh Long").orElse(null);
Author author2 = this.authorRepository.queryFindByName("Martin Kleppmann").orElse(null);
System.out.printf("queryFindByName(): author1 = %s%n", author1);
System.out.printf("queryFindByName(): author2 = %s%n", author2);
}
private void findByPartialName() {
Author author1 = this.authorRepository.findByNameContainingIgnoreCase("sh lo").orElse(null);
Author author2 = this.authorRepository.findByNameContainingIgnoreCase("in kl").orElse(null);
System.out.printf("findByPartialName(): author1 = %s%n", author1);
System.out.printf("findByPartialName(): author2 = %s%n", author2);
}
private void findById(List<Author> authors) {
Author author1 = this.authorRepository.findById(authors.get(0).getId()).orElse(null);
Author author2 = this.authorRepository.findById(authors.get(1).getId()).orElse(null);
System.out.printf("findById(): author1 = %s%n", author1);
System.out.printf("findById(): author2 = %s%n", author2);
}
private void listAllAuthors() {
List<Author> authors = this.authorRepository.findAll();
for (Author author : authors) {
System.out.printf("listAllAuthors(): author = %s%n", author);
for (Book book : author.getBooks()) {
System.out.printf("\t%s%n", book);
}
}
}
private List<Author> insertAuthors() {
Author author1 = this.authorRepository.save(new Author(null, "Josh Long",
Set.of(new Book(null, "Reactive Spring"), new Book(null, "Cloud Native Java"))));
Author author2 = this.authorRepository.save(
new Author(null, "Martin Kleppmann", Set.of(new Book(null, "Designing Data Intensive Applications"))));
System.out.printf("insertAuthors(): author1 = %s%n", author1);
System.out.printf("insertAuthors(): author2 = %s%n", author2);
return Arrays.asList(author1, author2);
}
}

View File

@@ -0,0 +1,28 @@
/*
* Copyright 2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.data.jpa;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DataJpaApplication {
public static void main(String[] args) throws InterruptedException {
SpringApplication.run(DataJpaApplication.class, args);
}
}

View File

@@ -0,0 +1,87 @@
/*
* Copyright 2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.data.jpa.model;
import java.util.Objects;
import java.util.Set;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
@Entity
public class Author {
@Id
@GeneratedValue
private Long id;
private String name;
@OneToMany(cascade = CascadeType.ALL)
private Set<Book> books;
protected Author() {
}
public Author(Long id, String name, Set<Book> books) {
this.id = id;
this.name = name;
this.books = books;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Book> getBooks() {
return books;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Author author = (Author) o;
return Objects.equals(id, author.id) && Objects.equals(name, author.name)
&& Objects.equals(books, author.books);
}
@Override
public int hashCode() {
return Objects.hash(id, name, books);
}
@Override
public String toString() {
return "Author{" + "name='" + name + '\'' + '}';
}
}

View File

@@ -0,0 +1,75 @@
/*
* Copyright 2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.data.jpa.model;
import java.util.Objects;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
@Entity
public class Book {
@Id
@GeneratedValue
private Long id;
private String title;
protected Book() {
}
public Book(Long id, String title) {
this.id = id;
this.title = title;
}
public Long getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Book book = (Book) o;
return Objects.equals(id, book.id) && Objects.equals(title, book.title);
}
@Override
public int hashCode() {
return Objects.hash(id, title);
}
@Override
public String toString() {
return "Book{" + "title='" + title + '\'' + '}';
}
}

View File

@@ -0,0 +1,12 @@
create table author
(
id bigint auto_increment primary key,
name varchar not null
);
create table book
(
id bigint auto_increment primary key,
author bigint not null references author (id),
title varchar not null
);

View File

@@ -0,0 +1,14 @@
package com.example.data.jpa;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class DataJpaApplicationTests {
@Test
void contextLoads() {
}
}

View File

@@ -28,6 +28,7 @@
<module>showcase</module>
<module>vavr</module>
<module>multitenant</module>
<module>graalvm-native</module>
</modules>
<profiles>