Skip to content

Tutorial: Hello Speedment

Per-Åke Minborg edited this page Nov 16, 2017 · 79 revisions

Tutorial: Hello Speedment

In this tutorial we will write a small application that asks for the users name and age and persist it in a mysql database. First of, 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 Maven project

The GUI before any generation

In your favorite IDE, create a new Maven project and make sure the project is using Java 8, if you do not use Java 8 or above, the code will not work at all.

Then add the following to your project's pom.xml-file:

MySQL

<build>
    <plugins>
        ...
        <plugin>
            <groupId>com.speedment</groupId>
            <artifactId>speedment-maven-plugin</artifactId>
            <version>3.0.18</version>
        </plugin>
        ...
    </plugins>
</build>
<dependencies>
    ...
    <dependency>
        <groupId>com.speedment</groupId>
        <artifactId>runtime</artifactId>
        <version>3.0.17</version>
        <type>pom</type>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.42</version>
    </dependency>
    ...
</dependencies>

PostgreSQL

<build>
    <plugins>
        ...
        <plugin>
            <groupId>com.speedment</groupId>
            <artifactId>speedment-maven-plugin</artifactId>
            <version>3.0.18</version>
        </plugin>
        ...
    </plugins>
</build>
<dependencies>
    ...
    <dependency>
        <groupId>com.speedment</groupId>
        <artifactId>runtime</artifactId>
        <version>3.0.17</version>
        <type>pom</type>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>9.4-1206-jdbc4</version>
    </dependency>
    ...
</dependencies>

MariaDB

<build>
    <plugins>
        ...
        <plugin>
            <groupId>com.speedment</groupId>
            <artifactId>speedment-maven-plugin</artifactId>
            <version>3.0.18</version>
        </plugin>
        ...
    </plugins>
</build>
<dependencies>
    ...
    <dependency>
        <groupId>com.speedment</groupId>
        <artifactId>runtime</artifactId>
        <version>3.0.17</version>
        <type>pom</type>
    </dependency>
    <dependency>
        <groupId>org.mariadb.jdbc</groupId>
        <artifactId>mariadb-java-client</artifactId>
        <version>2.1.2</version>
    </dependency>
    ...
</dependencies>

Make sure that you use the latest version of Speedment available.

Two new Maven targets will be available, speedment:generate and speedment:tool. generate is used to generate code from an existing .json project file and tool is used to connect to a database and create a json-file from that. We will use the tool command.

Maven targets

The first time the GUI launches, you will be able to fill out your email adress to join our java-community.

Enter your email adress

Connect to your database. The Open Source version supports open source database managers. Remember to fill out the name of the database schema at the bottom!

Enter your database credentials

Inside the GUI, you can either change the configuration using the controls or just go ahead and press Generate code!

Press the generate button

Done! Speedment has generated models for every table in the database! You can now switch back to your IDE and start coding or you can go back to the GUI to further configure the generation.

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().build();
        UserManager users = app.getOrThrow(UserManager.class);
    }
}

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()
    .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(
    new UserImpl()
        .setName(name)
        .setAge(age)
);

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

try {
    User user = new UserImpl()
        .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()
    .withLogging(PERSIST)
    .build();
UserManager users = app.getOrThrow(UserManager.class);

users.persist(
    new UserImpl()
        .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!