SPiedra955 / jdbc

This is a repo where I use java file to connect a database with using a pool connection, jpa-hibernate and jdbc

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Database connection with JDBC

Table of contents

Introduction

This is a project in which we are going to use a Java Database Connectivity (JDBC) is an API that implements a set of interfaces, which allow a Java application to interact with a database, such as opening a connection, sending SQL commands and receiving information returned from the database.

We also have to implement maven for this project and make use of its folder structure and configuration to import libraries and drivers.

Requirements

  • First we need to have an IDE with a Java installed.
  • Second once we have Java installed it's necessary install maven for set up our project.
  • Third you must have a SQL server installed, in this case I am going to use MariaDB.

In my case I have created this project from scratch using VSCode with maven, the following link is to install VSCode, Java and maven to set up on a windows system. 👇

Java - Configurar Visual Studio Code y Maven

Starting a project with Maven

  • Inside our IDE (VSC) once you have all the requirements of the previous section, press the keys Ctrl + Shift + p and write Maven: Update maven archetype Catalog
  • Again Ctrl + Shift + p and write Java: Create Java Project

gitignore - jdbc - Visual Studio Code 14_04_2023 18_15_59

  • Then select the project type in this case Maven

gitignore - jdbc - Visual Studio Code 14_04_2023 18_19_11

  • Select maven-archetype-quickstart

gitignore - jdbc - Visual Studio Code 14_04_2023 18_20_56

  • Archetype version 1.4

gitignore - jdbc - Visual Studio Code 14_04_2023 18_21_03

  • Give a group Id to your project

gitignore - jdbc - Visual Studio Code 14_04_2023 18_21_10

  • Give an artifact Id to your project

gitignore - jdbc - Visual Studio Code 14_04_2023 18_21_13

  • Select the folder destination

image

  • Expected output and name the version of your project

gitignore - jdbc - Visual Studio Code 14_04_2023 18_22_13

  • Open the project

gitignore - jdbc - Visual Studio Code 14_04_2023 18_22_47

  • Final result

Visual Studio Code 14_04_2023 18_23_20

First connection to database

Before starting, a previously created database is needed Choose in your workspace pom.xml (Click to view the file) and add the JDBC Driver (check the last version)

<dependency>
   <groupId>org.mariadb.jdbc</groupId>
   <artifactId>mariadb-java-client</artifactId>
   <version>LATEST</version>
</dependency>

Create a Java class for example ConnectionJDBC.java (Click to view the file) This code establishes a connection to a MariaDB database using JDBC. First, it defines a class called "ConnectionJDBC" which contains a main method that calls two methods: "initDatabaseConnection()" to establish the connection and "closeDatabaseConnection()" to close the connection. The connection is established by using a URL, username and password. The program prints whether the connection is valid after establishing and closing the connection.

Expected output for this file:

image

CRUD

In this section we implement the execution of SELECT, INSERT, UPDATE and DELETE statements in a SQL database using JDBC. This file contains the code to generate a table inside a database (you have to create it before) and execute operations such as create, read, update and delete. Check the file Crud.java.

_Expected output for this file

image

In the image above we insert some values for students such as personal data and their grades for a course where by default the value approved is false, when we update the values they are set to true if the grade is equal or higher than 5 and finally a student is dropped because he/she leaves the course.

Connection Pool

A connection pool maintains a number of open database connections and this number can vary depending on the load of the service. So instead of opening a new connection yourself, you simply request one of the available connections, thus improving the performance of your application. Not closing your connections and opening new ones every time you need them is a waste of resources and will lead to poor performance.

Configure dependencies

These are the dependencies you need to add to your pom.xml

<dependency>
   <groupId>com.zaxxer</groupId>
   <artifactId>HikariCP</artifactId>
   <version>5.0.0</version>
</dependency>
  
<dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-simple</artifactId>
   <version>1.8.0-beta4</version>
</dependency>

Create a Java class

Create a class like ConnectionPool.java

HikariCP

HikariCP is the library that we will use to make the connection pool, it needs information that specifies the database, user, password, port. This information can be located in the same file or inside a folder in the project, in this case it is located in the Java class.

Here is the main repo of the hikari developers if you want to configure the hikari file in another way.

Example:

 private static void initDatabaseConnectionPool() {
            dataSource = new HikariDataSource();
            dataSource.setJdbcUrl("jdbc:mariadb://localhost:[db_port]/[db_name]");
            dataSource.setUsername("[db_user]");
            dataSource.setPassword("[db_password]");
        }

Expected output for this file:

image

Connection using JPA

JPA

JPA stands for Java Persistence API. It is a Java specification that provides a framework for managing relational data in Java applications. JPA defines a set of interfaces and annotations that allows developers to easily map Java objects to relational database tables and perform CRUD (Create, Read, Update, Delete) operations using standard Java objects and methods. JPA also provides a way to query data using a simple and powerful query language called JPQL (Java Persistence Query Language), which is similar to SQL but operates on Java objects rather than database tables.

Dependencies

<dependency>
    <groupId>org.mariadb.jdbc</groupId>
    <artifactId>mariadb-java-client</artifactId>
    <version>LATEST</version>
</dependency>

<dependency>
    <groupId>jakarta.persistence</groupId>
    <artifactId>jakarta.persistence-api</artifactId>
    <version>3.0.0</version>
</dependency>
  
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core-jakarta</artifactId>
    <version>5.6.4.Final</version>
</dependency>
  
<dependency>
    <groupId>org.glassfish.jaxb</groupId>
    <artifactId>jaxb-runtime</artifactId>
    <version>3.0.0</version>
</dependency>

Files

Products.java This file contains the code to create the table and its fields, the methods are defined and very intuitive to understand.

JpaService.java This code allows executing functions inside a transaction in a JPA database. The class has a runInTransaction() method that takes a function as an argument and executes it inside a transaction. If the function executes successfully, the transaction is committed, otherwise a rollback is performed. The class also has methods to initialise and close the database connection.

ApplicationJPA.java This file uses the JpaService class to create and retrieve objects from the JPA database. In its main() method, it first calls the createProducts() method which creates some Products objects with random names and prices and stores them in the database. Then, it calls the printProducts() method that executes a JPA query to retrieve all the products that have a price greater than 5 and displays them by console. The file is a sample application that demonstrates how to use the JpaService class to interact with a JPA database.

Database connection

You have to create a folder called resources inside create another folder as META-INF with a file called persistence.xml and specify your database information.

The path for this folder it's important and should have a path like this src\main\resources\META-INF\persistence.xml

Expected output:

image

About

This is a repo where I use java file to connect a database with using a pool connection, jpa-hibernate and jdbc


Languages

Language:Java 100.0%