Membuat CRUD menggunakan Quarkus + MYSQL
Quarkus adalah framework aplikasi yang didesain untuk Java virtual machine (JVM) dan native compilation yang cepat dan efisien. Framework ini sangat cocok untuk membangun microservices, terutama untuk lingkungan cloud dan Kubernetes. Quarkus memiliki beberapa keunggulan, di antaranya startup time yang sangat cepat, konsumsi memori yang rendah, dan dukungan untuk GraalVM yang memungkinkan aplikasi Java di-compile menjadi native executables.
Berikut adalah penjelasan singkat tentang beberapa fitur utama Quarkus:
- Startup Time yang Cepat: Quarkus dirancang untuk memiliki waktu startup yang sangat cepat, membuatnya ideal untuk aplikasi dengan permintaan tinggi dan aplikasi cloud-native.
- Konsumsi Memori yang Rendah: Quarkus mengkonsumsi lebih sedikit memori dibandingkan framework Java tradisional, memungkinkan aplikasi berjalan lebih efisien pada lingkungan dengan sumber daya terbatas.
- Dukungan Native Image: Dengan GraalVM, aplikasi Quarkus dapat dikompilasi menjadi native executable, yang berarti aplikasi dapat berjalan tanpa JVM, meningkatkan performa dan efisiensi.
- Developer Joy: Quarkus menyediakan fitur seperti live reload, yang memungkinkan pengembang melihat perubahan kode secara langsung tanpa harus me-restart aplikasi, meningkatkan produktivitas.
iex "& { $(iwr https://ps.jbang.dev) } trust add https://repo1.maven.org/maven2/io/quarkus/quarkus-cli/"
iex "& { $(iwr https://ps.jbang.dev) } app install --fresh --force quarkus@quarkusio"
iex "& { $(iwr https://ps.jbang.dev) } trust add https://repo1.maven.org/maven2/io/quarkus/quarkus-cli/"
iex "& { $(iwr https://ps.jbang.dev) } app install --fresh --force quarkus@quarkusio"
iex "& { $(iwr https://ps.jbang.dev) } app setup"
C:\Program Files\Apache\Maven
.- Buka Menu Start, search for "Environment Variables", dan select "Edit the system environment variables".
- Dalam System Properties window, Jangan lupa klik "Environment Variables" button.
- Dibawah "System variables", klik"New" dan tambahkan
M2_HOME
dengan nilai Maven directory kamu ya, contohC:\Program Files\Apache\Maven\apache-maven-3.9.7
. - Temukan dan select
Path
variabel, kemudian klik "Edit". tambahkan Mavenbin
directory to the PATH, e.g.,C:\Program Files\Apache\Maven\apache-maven-3.9.7\bin
.
quarkus create app
code-with-quarkuspom.xml
:<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-hibernate-orm-panache</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-resteasy</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-resteasy-jackson</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-jdbc-mysql</artifactId>
</dependency>
-------------------------------------------------------------
Kalo kode pom.xml saya seperti ini :<?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.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.perconaan.code</groupId> <artifactId>code-with-quarkus</artifactId> <version>1.0.0-SNAPSHOT</version>
<properties> <compiler-plugin.version>3.12.1</compiler-plugin.version> <maven.compiler.release>17</maven.compiler.release> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <quarkus.platform.artifact-id>quarkus-bom</quarkus.platform.artifact-id> <quarkus.platform.group-id>io.quarkus.platform</quarkus.platform.group-id> <quarkus.platform.version>3.11.1</quarkus.platform.version> <skipITs>true</skipITs> <surefire-plugin.version>3.2.5</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-hibernate-orm-panache</artifactId> </dependency> <dependency> <groupId>io.quarkus</groupId> <artifactId>quarkus-resteasy</artifactId> </dependency> <dependency> <groupId>io.quarkus</groupId> <artifactId>quarkus-resteasy-jackson</artifactId> </dependency> <dependency> <groupId>io.quarkus</groupId> <artifactId>quarkus-jdbc-mysql</artifactId> </dependency> <dependency> <groupId>io.quarkus</groupId> <artifactId>quarkus-arc</artifactId> </dependency> <dependency> <groupId>io.quarkus</groupId> <artifactId>quarkus-hibernate-orm</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>${quarkus.platform.group-id}</groupId> <artifactId>quarkus-maven-plugin</artifactId> <version>${quarkus.platform.version}</version> <extensions>true</extensions> <executions> <execution> <goals> <goal>build</goal> <goal>generate-code</goal> <goal>generate-code-tests</goal> </goals> </execution> </executions> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>${compiler-plugin.version}</version> <configuration> <compilerArgs> <arg>-parameters</arg> </compilerArgs> </configuration> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>${surefire-plugin.version}</version> <configuration> <systemPropertyVariables> <java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager> <maven.home>${maven.home}</maven.home> </systemPropertyVariables> </configuration> </plugin> <plugin> <artifactId>maven-failsafe-plugin</artifactId> <version>${surefire-plugin.version}</version> <executions> <execution> <goals> <goal>integration-test</goal> <goal>verify</goal> </goals> </execution> </executions> <configuration> <systemPropertyVariables> <native.image.path>${project.build.directory}/${project.build.finalName}-runner</native.image.path> <java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager> <maven.home>${maven.home}</maven.home> </systemPropertyVariables> </configuration> </plugin> </plugins> </build>
<profiles> <profile> <id>native</id> <activation> <property> <name>native</name> </property> </activation> <properties> <skipITs>false</skipITs> <quarkus.native.enabled>true</quarkus.native.enabled> </properties> </profile> </profiles></project>
3. Konfigurasi Database:
Tambahkan konfigurasi database di file application.properties
:properties :# Configure the HTTP port for Quarkusquarkus.http.port=9090# Database configurationquarkus.datasource.db-kind=mysqlquarkus.datasource.username=javadeveloperquarkus.datasource.password=joko24051992quarkus.datasource.jdbc.url=jdbc:mysql://localhost:3306/testdb# Hibernate ORMquarkus.hibernate-orm.database.generation=updatequarkus.hibernate-orm.log.sql=true# Pooling configurationquarkus.datasource.jdbc.max-size=8quarkus.datasource.jdbc.min-size=2
Item
:
Buat kelas Item
di package org.perconaan.code:package org.perconaan.code;import io.quarkus.hibernate.orm.panache.PanacheEntity;import jakarta.persistence.Entity;/*** Example JPA entity defined as a Panache Entity.* An ID field of Long type is provided, if you want to define your own ID field extends <code>PanacheEntityBase</code> instead.** This uses the active record pattern, you can also use the repository pattern instead:* .** Usage (more example on the documentation)** {@code* public void doSomething() {* MyEntity entity1 = new MyEntity();* entity1.field = "field-1";* entity1.persist();** List<MyEntity> entities = MyEntity.listAll();* }* }*/@Entitypublic class Item extends PanacheEntity {public String name;public int quantity;public double price;public double total;public void calculateTotal() {this.total = this.quantity * this.price;}}
ItemResource
di package org.perconaan.code:package org.perconaan.code;import java.util.List;import jakarta.transaction.Transactional;import jakarta.ws.rs.*;import jakarta.ws.rs.core.MediaType;import jakarta.ws.rs.core.Response;@Path("/items")@Produces(MediaType.APPLICATION_JSON)@Consumes(MediaType.APPLICATION_JSON)public class ItemResource {@GET@Produces(MediaType.TEXT_PLAIN)public String hello() {return "Hello RESTEasy";}@GETpublic List<Item> getAllItems() {return Item.listAll();}@GET@Path("/{id}")public Item getItem(@PathParam("id") Long id) {return Item.findById(id);}@POST@Transactionalpublic Response createItem(Item item) {item.calculateTotal();item.persist();return Response.status(Response.Status.CREATED).entity(item).build();}@PUT@Path("/{id}")@Transactionalpublic Item updateItem(@PathParam("id") Long id, Item item) {Item entity = Item.findById(id);if (entity == null) {throw new WebApplicationException("Item with id " + id + " does not exist.", Response.Status.NOT_FOUND);}entity.name = item.name;entity.quantity = item.quantity;entity.price = item.price;entity.calculateTotal();entity.persist();return entity;}@DELETE@Path("/{id}")@Transactionalpublic Response deleteItem(@PathParam("id") Long id) {Item entity = Item.findById(id);if (entity == null) {throw new WebApplicationException("Item with id " + id + " does not exist.", Response.Status.NOT_FOUND);}entity.delete();return Response.noContent().build();}}
6. Jalankan Aplikasi: Jalankan aplikasi dengan perintah:
Running program di directory progrm kita menggunakan bash/powershell/cmd :./mvnw compile quarkus:dev
jika berhasil maka akan tampil seperti berikut :
Testing menggunakan PostMan :
Methode POST :
http://localhost:9090/itemsMethode GET :
http://localhost:9090/items/1Methode PUT :
http://localhost:9090/items/1Methode DELETE :
http://localhost:9090/items/1
Comments
Post a Comment