QUARKUS + Hibernate CRUD example - Creating a CRUD REST API/Service
Quarkus is a Java framework designed to run within containers. Fixating on expeditious start-up times and low memory utilization makes it more felicitous to run within container orchestration platforms like Kubernetes.Quarkus supports many industry-standard libraries such as Hibernate, Kubernetes, RESTEasy, Eclipse MicroProfile, and more...
Let's start to build RESTful API with QUARKUS
Technologies used:
- Quarkus 2.2.3.Final
- Hibernate
- H2 Database
- Java 11
Project Directory
Maven Dependencies[pom.xml]
A Project Object Model or POM is the fundamental unit of work in Maven. It is an XML file that contains information about the project and configuration details utilized by Maven to build the project. It contains default values for most projects. Some of the configurations that can be designated in the POM is the project dependencies, the plugins or goals that can be executed, the build profiles, and so on. Other information such as the project version, description, developers, mailing lists, and such can withal be designated.
<?xml version="1.0" encoding="UTF-8"?><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.0http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.knf.dev</groupId><artifactId>quarkus-hibernate-crud</artifactId><version>1.0</version><properties><compiler-plugin.version>3.8.1</compiler-plugin.version><maven.compiler.parameters>true</maven.compiler.parameters><maven.compiler.source>11</maven.compiler.source><maven.compiler.target>11</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><quarkus-plugin.version>2.2.3.Final</quarkus-plugin.version><quarkus.platform.artifact-id>quarkus-universe-bom</quarkus.platform.artifact-id><quarkus.platform.group-id>io.quarkus</quarkus.platform.group-id><quarkus.platform.version>2.2.3.Final</quarkus.platform.version><surefire-plugin.version>2.22.1</surefire-plugin.version></properties><dependencyManagement><dependencies><dependency><groupId>${quarkus.platform.group-id}</groupId><artifactId>${quarkus.platform.artifact-id}</artifactId><version>${quarkus.platform.version}</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><dependencies><dependency><groupId>io.quarkus</groupId><artifactId>quarkus-resteasy-jsonb</artifactId></dependency><dependency><groupId>io.quarkus</groupId><artifactId>quarkus-hibernate-orm</artifactId></dependency><dependency><groupId>io.quarkus</groupId><artifactId>quarkus-jdbc-h2</artifactId></dependency><dependency><groupId>io.quarkus</groupId><artifactId>quarkus-junit5</artifactId><scope>test</scope></dependency><dependency><groupId>io.rest-assured</groupId><artifactId>rest-assured</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>io.quarkus</groupId><artifactId>quarkus-maven-plugin</artifactId><version>${quarkus-plugin.version}</version><executions><execution><goals><goal>build</goal></goals></execution></executions></plugin><plugin><artifactId>maven-compiler-plugin</artifactId><version>${compiler-plugin.version}</version></plugin><plugin><artifactId>maven-surefire-plugin</artifactId><version>${surefire-plugin.version}</version><configuration><systemProperties><java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager></systemProperties></configuration></plugin></plugins></build><profiles><profile><id>native</id><activation><property><name>native</name></property></activation><build><plugins><plugin><artifactId>maven-failsafe-plugin</artifactId><version>${surefire-plugin.version}</version><executions><execution><goals><goal>integration-test</goal><goal>verify</goal></goals><configuration><systemProperties><native.image.path>${project.build.directory}/${project.build.finalName}-runner</native.image.path></systemProperties></configuration></execution></executions></plugin></plugins></build><properties><quarkus.package.type>native</quarkus.package.type></properties></profile></profiles></project>
application.properties
# datasource configuration
quarkus.datasource.db-kind = h2
quarkus.datasource.username = sa
# quarkus.datasource.password =
quarkus.datasource.jdbc.url = jdbc:h2:mem:test
# drop and create the database at startup (use `update` to only update the
schema)
quarkus.hibernate-orm.database.generation=drop-and-create
quarkus.hibernate-orm.sql-load-script = data.sql
data.sql [Dummy data]
INSERT INTO users (id, firstName, lastName, emailId) VALUES
(19871343, 'Sibin', 'knf', 'sibincheck@gmail.com');
INSERT INTO users (id, firstName, lastName, emailId) VALUES
(3434419871, 'Sabin', 'knf', 'sibintest@gmail.com');
Entity class(User.class) - ORM
The @Entity annotation specifies that the class is an entity and is mapped to a database table. The @Id annotation specifies the primary key of an entity and the @GeneratedValue provides for the specification of generation strategies for the values of primary keys.
package com.knf.dev;
import javax.persistence.*;
import java.io.Serializable;
@Table(name = "users")
@Entity
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
private String emailId;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public User(Long id, String firstName, String lastName, String emailId) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.emailId = emailId;
}
public User() {
super();
}
}
UserResource.class
package com.knf.dev;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import java.util.List;
@Singleton
public class UserResource {
@Inject
EntityManager entityManager;
public List<User> getUsers() {
return entityManager.createQuery("SELECT c FROM User c").
getResultList();
}
public User getUser(Long id) {
return entityManager.find(User.class, id);
}
@Transactional(Transactional.TxType.REQUIRED)
public User addUser(User user) {
entityManager.persist(user);
return user;
}
@Transactional(Transactional.TxType.REQUIRED)
public void updateUser(Long id, User user) {
User userToUpdate = entityManager.find(User.class, id);
if (null != userToUpdate) {
userToUpdate.setFirstName(user.getFirstName());
userToUpdate.setLastName(user.getLastName());
userToUpdate.setEmailId(user.getEmailId());
} else {
throw new RuntimeException("No such user available");
}
}
@Transactional(Transactional.TxType.REQUIRED)
public void deleteUser(Long id) {
User user = getUser(id);
entityManager.remove(user);
}
}
UserEndpoint.class
package com.knf.dev;
import java.util.List;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/api/users")
public class UserEndpoint {
@Inject
UserResource userResource;
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<User> getUsers() {
return userResource.getUsers();
}
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public User getUser(@PathParam("id") Long id) {
return userResource.getUser(id);
}
@PUT
@Path("/{id}")
@Consumes(MediaType.APPLICATION_JSON)
public void updateUser(@PathParam("id") Long id, User user) {
userResource.updateUser(id, user);
}
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public User addUser(User user) {
return userResource.addUser(user);
}
@DELETE
@Path("/{id}")
public void deleteUser(@PathParam("id") Long id) {
userResource.deleteUser(id);
}
}
Verify REST APIs
Build application jar file: mvn clean package
Start application: java -jar quarkus-run.jar
1. Get all users
2. Get single user
3. Add user