Skip to content

Tutorial: Hello Speedment

Mislav Milicevic edited this page Nov 8, 2019 · 79 revisions

In this tutorial, we will write a small application that asks for the user's name and age and persists it in a MySQL database. First off, we will initialize the database.

Step 1: Setup the database

CREATE DATABASE hellospeedment;
USE hellospeedment;

We will also add a table for storing the information.

CREATE TABLE IF NOT EXISTS `user` (
    `id` bigint(20) NOT NULL AUTO_INCREMENT,
    `name` varchar(32) NOT NULL,
    `age` int(5) NOT NULL,
    PRIMARY KEY (`id`),
    UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

Step 2: Create a new Speedment Maven project

We explain how this is done in our Quick Start guides Start a New Speedment Maven Project and Connect to Your Database.

When you are done, you should end up with this structure:

Back to your IDE

Step 3: Write the application

Initializing Speedment is really easy. Create a java Main file and write the following line:

package com.company.speedment.test.hellospeedment;

/**
 *
 * @author Your name
 */
public class Main {
    public static void main(String... params) {
        HellospeedmentApplication app = new HellospeedmentApplicationBuilder()
            .withBundle(MySqlBundle.class)
            .build();
        UserManager users = app.getOrThrow(UserManager.class);
    }
}

In order to tell Speedment what database it will be interacting with, with must add a connector bundle when creating our application instance. This is done by calling withBundle(CONNECTOR_BUNDLE) as shown in the previous example. Since we are using MySQL, we will be adding the MySqlBundle.

The HellospeedmentApplication-instance is generated automatically by Speedment and will connect to the database and handle all the initialization for you! If you have a password on your MySQL database, you will need to set that manually like this:

HellospeedmentApplication app = new HellospeedmentApplicationBuilder()
    .withBundle(MySqlBundle.class)
    .withPassword("YourSuperSecretPassword")
    .build();

Speedment takes your security seriously and will not store your passwords in any configuration files.

Now we will listen to user input. To do this, we use a Scanner on the standard input channel.

final Scanner scn = new Scanner(System.in);

Using the scanner we can ask the user for a name and an age. We will not check the validity of the input in this tutorial so we just assume the user inputs everything correctly.

System.out.print("What is your name? ");
final String name = scn.nextLine();

System.out.print("What is your age? ");
final int age = scn.nextInt();

Now we want to persist this information to the database. This is done by creating a new entity, setting its values, and calling persist() on it.

users.persist(
    users.create()
        .setName(name)
        .setAge(age)
);

We can also react to the query, printing a message if anything failed. This could for an example happen if the name is already persisted.

try {
    User user = users.create()
        .setName(name)
        .setAge(age);
    user = users.persist(user);
    System.out.print("Hello, " + user.getName() + "!");
} catch (SpeedmentException se) {
   System.out.print("Why are you so persistent?");
   se.printStackTrace();
}

If you want to know exactly what is happening with your persist() command, you can set up the application for logging as follows.

HellospeedmentApplication app = new HellospeedmentApplicationBuilder()
    .withBundle(MySqlBundle.class)
    .withLogging(PERSIST)
    .build();
UserManager users = app.getOrThrow(UserManager.class);

users.persist(
    users.create()
        .setName(name)
        .setAge(age)
);

This might give the following output:

What is your name? John Smith
What is your age? 32
sql = insert into hellospeedment.user(id, name, age) values (?, ?, ?)
params = [null, John Smith, 32]
thowable = 

If you enter the same name again you might get this output:

What is your name? John Smith
What is your age? 10
sql = insert into hellospeedment.user(id, name, age) values (?, ?, ?)
params = [null, John Smith, 10]
thowable = Duplicate entry 'John Smith' for key 'name'

This was all for this tutorial!