Quarkus Database Connectivity Example

Sure! Quarkus is a popular Java framework for building cloud-native applications, and it provides excellent support for database connectivity. Here’s an example of how you can connect to a PostgreSQL database using Quarkus:

Add the necessary dependencies to your project’s pom.xml file:

<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-jdbc-postgresql</artifactId>
</dependency>
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-hibernate-orm-panache</artifactId>
</dependency>

Configure the PostgreSQL database connection in the application.properties file located in the src/main/resources directory:

quarkus.datasource.url=jdbc:postgresql://localhost:5432/mydatabase
quarkus.datasource.driver=org.postgresql.Driver
quarkus.datasource.username=myuser
quarkus.datasource.password=mypassword
quarkus.hibernate-orm.database.generation=update

Make sure to replace localhost, mydatabase, myuser, and mypassword with the appropriate values for your PostgreSQL setup.

Create an entity class representing a table in your database. For example, let’s create a Person entity:

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Person {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    private String name;
    private int age;
    
    // getters and setters
    
}

Create a repository interface that extends PanacheRepository<Person>. This interface provides CRUD operations for your entity:

import io.quarkus.hibernate.orm.panache.PanacheRepository;

public interface PersonRepository extends PanacheRepository<Person> {
}

Now you can use the PersonRepository in your Quarkus application to interact with the database. For example, you can inject the repository into a resource class and perform CRUD operations:

import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.List;

@Path("/persons")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class PersonResource {

    @Inject
    PersonRepository personRepository;
    
    @GET
    public List<Person> getAllPersons() {
        return personRepository.listAll();
    }
    
    @POST
    public Person createPerson(Person person) {
        personRepository.persist(person);
        return person;
    }
    
    // Other resource methods for updating, deleting, etc.
}

That’s it! You now have a Quarkus application with database connectivity to PostgreSQL using Hibernate and JPA. You can run the application and test the endpoints to interact with the Person entity in the database.

Leave a Reply

Your email address will not be published. Required fields are marked *