days
-4
-1
hours
0
-6
minutes
-1
-4
seconds
0
-7
search
JAX Developers Puzzle deadline approaching: Play for a chance to win a complimentary JAX London 2018 ticket!
Taking Speedment for a spin

Creating database content with Java 8

Per Minborg

Per Minborg, founder and CTO at the Speedment AB, reminisces about the old (Java) days when people were experimenting with Java and databases and paves the way for Speedment, the Java 8 Open Source project which can be used to extract Java code from existing database schemas without trouble and directly start coding applications.

I still remember the old (Java) days when we were staying up late and experimenting a lot with Java and databases. When the Java era was still in its infancy there was not much support for database connectivity and so we had to basically write our own database classes and handle ResultSets, Connections and SQLExceptions by ourselves.

Nowadays we expect simple things to just happen! Let’s say we have an existing database and we want to add or update information in it using a Java application. How can we do that in a simple way without having to write a lot of boilerplate code?

I have contributed a lot to the Java 8 Open Source project Speedment, which can be used to extract Java code from existing database schemas without trouble and directly start coding applications.

Let’s take it for a spin.

Example

Let’s say we have a MySQL database table that is supposed to contain data on various countries. The table could look something like this:

 

mysql> explain country +————+————-+——+—–+———+—————-+ | Field | Type | Null | Key | Default | Extra | +————+————-+——+—–+———+—————-+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(45) | YES | UNI | NULL | | | local_name | varchar(45) | YES | | NULL | | | code | int(11) | YES | | NULL | | | domain | varchar(10) | YES | | NULL | +————+————-+——+—–+———+—————-+ 5 rows in set (0.00 sec)

 

Let us further pretend that we have the task of populating the table with a few countries and see how that can be solved.

Setting up the Speedment project

In order to set up a project with Speedment, we need to include a few lines in our POM.xml file, connect to the database and generate code. Read more on how to do this here! You can also check out this film which shows you exactly how easy it is to create a project with Speedment.

Initializing the database connection

Now that our database domain model is generated automatically, we can begin the actual coding to insert data into the database. First, we need to set up our Java 8 database project like this:

// Setup Speedment speedment = new JavapotApplication().withPassword(“javapot”).build(); Manager countries = speedment.managerOf(Country.class);

The JavapotApplication class was generated automatically from the database schema and contains all meta data (such as columns and tables) of the database. Keep in mind that we manually need to provide the password since this is not stored in the meta data model (for security reasons). The countries variable is a “handle” for the table we are about to work with.

There is really no “magic” going on with the generation. We can see all the generated Java files in clear text and we can change them or introduce our own versions if we want.

Inserting data in the database

Once the setup is made, it is very easy to insert data rows in the database like this.

try {
  countries.newInstance()
  .setName("United States")
  .setLocalName("United States")
  .setCode(1)
  .setDomain(".us")
  .persist();
  countries.newInstance()
  .setName("Germany")
  .setLocalName("Deutschland")
  .setCode(49)
  .setDomain(".de")
  .persist();
  // Needless to say, you can call the setters in any order.
  countries.newInstance()
  .setDomain(".uk")
  .setCode(44)
  .setName("United Kingdom")
  .setLocalName("United Kingdom")
  .setDomain(".uk")
  .persist();
  countries.newInstance()
  .setName("Sweden")
  .setLocalName("Sverige")
  .setCode(40) // Intentionally wrong, should be 46!!
  .setDomain(".se")
  .persist();
} catch (SpeedmentException se) {
  // Handle the exception here
}

The newInstance() method creates a new empty Country object, which means that we just use the setters to initialize the country. After all parameters are set, we call the persist() method to store the object in the database. If there is an error during the database insert, a SpeedmentException will be thrown, allowing you to examine the cause (for example if you are trying to insert two countries with the same name).  I intentionally picked the wrong country call code for Sweden (förlåt Sverige) so that we can learn how to update data in our database too.

Updating data in the database

If you want to update an existing row in the database you can do it like this:

countries.stream()
.filter(Country.NAME.equal("Sweden"))
.findAny()
.ifPresent(c -> c.setCode(46).update());

This will create a Stream with all the counties that have the name “Sweden” (which, evidently, is only one country) and then it will try to find that country. If it is present, it will take that country and set the code to 46 (which is the correct calling code for Sweden) and then update the selected country in the database. It is important to understand that even though our country table might contain a large number of countries, it will only include those countries in the stream that are satisfying an equivalent query of “select * from country where name=’Sweden’ ” in this case. Now our database looks like the one here.

 

mysql> select * from country; +—-+—————-+—————-+——+——–+ | id | name | local_name | code | domain | +—-+—————-+—————-+——+——–+ | 1 | United States | United States | 1 | .us | | 2 | Germany | Deutschland | 49 | .de | | 3 | United Kingdom | United Kingdom | 44 | .uk | | 4 | Sweden | Sverige | 46 | .se | +—-+—————-+—————-+——+——–+ 4 rows in set (0.00 sec)

 

Success! Mission accomplished!

Contributing

Read more about Speedment Open Source here – this is also the place to be if you want to learn more things like how the API looks like and how you can use Speedment in your projects. Speedment can be found on GitHub. You can contribute by submitting comments on gitter or download the source code and create pull requests with your own code contributions.

Conclusions

With Java 8, you can easily write database applications with almost no extra manual code work. There are tools that can automatically extract your domain model from a database schema.

These days, we, Java programmers can spend more time on the actual problem (and perhaps get some more well-deserved sleep) instead of fiddling around with basic database functionality.

Author
Per Minborg
Per-Åke Minborg is founder and CTO at the Speedment AB. He has worked in numerous international projects and systems management for new radio systems, GSM / EDGE radio standardization within ETSI. He has generated +100 patent applications and invention disclosures within the field of radio communication, information security, cloud-technology and graph database technology.He has previously served as CTO and founder of Phone Pages AB. Per-Åke has a M.Sc. in Electrical Engineering from Chalmers University of Technology and several years of studies in computer science and computer security at university and PhD level.

Leave a Reply

Be the First to Comment!

avatar
400
  Subscribe  
Notify of