Java Code Walkthrough

Overview

This walkthrough explains how to perform a simple test of a SkySQL service using Java code, as described in our Quickstart experience.

Done with this walkthrough? Return to Step 3 of the Quickstart

Dependencies

  • Java Development Kit (JDK) 8 or later

  • Spring Boot 2.4.0 or later

  • Spring Data JPA

Install MariaDB Connector/J

Maven and Gradle can install MariaDB Connector/J as a dependency of your application during build.

Alternatively, you can install MariaDB Connector/J using JAR.

Maven

To install the example dependencies and the latest version of MariaDB Connector/J using Maven, add the following <parent> section and <dependencies> section to your pom.xml file:

<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.6.6</version>
  <relativePath /> <!-- lookup parent from repository -->
</parent>

<dependencies>
  <dependency>
    <groupId>org.mariadb.jdbc</groupId>
    <artifactId>mariadb-java-client</artifactId>
    <version>3.0.9</version>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
    <version>2.7.0</version>
  </dependency>
  <dependency>
    <groupId>javax.persistence</groupId>
    <artifactId>persistence-api</artifactId>
    <version>1.0.2</version>
  </dependency>
</dependencies>

Gradle

To install the example dependencies and the latest version of MariaDB Connector/J using Gradle, add the following to your build.gradle file:

compile "org.mariadb.jdbc:mariadb-java-client:3.0.9"

Prepare Code

Connect

Configure the connection by editing the application.properties file. Use the host, username, and password that you can get by clicking "CONNECT TO SERVICE" on the service listing on the "Your Services" page instead of the placeholder text that follows:

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MariaDBDialect
spring.datasource.url=jdbc:mariadb://quickstart.mdbxxxxxxx.db.skysql.net:5001/spring_demo?useSsl=true&serverSslCert=/path/to/skysql_chain.pem&createDatabaseIfNotExist=true
spring.datasource.username=DBXXXXXXXX
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

Create an Entity

Create the following JPA Entity in a ProgrammingLanguage.java file:

package com.example;

import java.util.Objects;

import javax.persistence.*;

@Entity
@Table(name = "programming_language")
public class ProgrammingLanguage {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "pl_id")
    private Integer id;

    @Column(name = "pl_name")
    private String name;

    @Column(name = "pl_rating")
    private Integer rating;

    public ProgrammingLanguage() {
    }

    public ProgrammingLanguage(String name, Integer rating) {
        this.name = name;
        this.rating = rating;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o)
            return true;
        if (o == null || getClass() != o.getClass())
            return false;
        ProgrammingLanguage that = (ProgrammingLanguage) o;
        return Objects.equals(id, that.id);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getRating() {
        return rating;
    }

    public void setRating(Integer rating) {
        this.rating = rating;
    }
}

Create a Repository

Create the following Repository in a ProgrammingLanguageRepository.java file:

package com.example;

import org.springframework.data.jpa.repository.JpaRepository;

public interface ProgrammingLanguageRepository extends
    JpaRepository<ProgrammingLanguage, Integer> {
}

Use the Repository

You can inject references of type ProgrammingLanguageRepository in any Spring-managed bean. For example, the following command line application saves objects of type ProgrammingLanguage in the database, loads them from the database, and prints their names in the output:

package com.example;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class Application {
    private final ProgrammingLanguageRepository repository;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    public Application(ProgrammingLanguageRepository repository) {
        this.repository = repository;
    }

    @Bean
    public ApplicationRunner applicationRunner() {
        return args -> {
            createProgrammingLanguages();
            printTopProgrammingLanguages();
        };
    }

    private void createProgrammingLanguages() {
        Map<String, Integer> data = Map.of(
            "Python", 10,
            "Java", 9,
            "C++", 8,
            "JavaScript", 7,
            "C#", 6,
            "Go", 5,
            "Rust", 4,
            "PHP", 3
            );
        Arrays.stream(data.keySet().toArray(new String[data.size()]))
            .map(name -> new ProgrammingLanguage(name, data.get(name)))
            .forEach(repository::save);
    }

    private void printTopProgrammingLanguages() {
        List<ProgrammingLanguage> programmingLanguages = repository.findAll();
        programmingLanguages.stream()
            .map(pl -> pl.getRating() + " - " + pl.getName())
            .forEach(System.out::println);
    }
}

Run the Test

Those using Maven can start the application by running the following command (or equivalent option in your IDE):

$ mvn spring-boot:run

You should see something similar to the following output among all the informational lines:

4 - Rust
8 - C++
9 - Java
6 - C#
7 - JavaScript
10 - Python
3 - PHP
5 - Go

Done with this walkthrough? Return to Step 3 of the Quickstart