I can then browse to http://localhost/users/1 and get the hard-coded user details back. Very simple.
Step 3 – Persisting data
Next, I needed a place to store my user data. I thought of using basic JDBC and creating some Data Access Object (DAO) classes but this, again, would take quite some time. I did some searching and came across a nice lightweight Java library that does all this for me. Ladies and Gentlemen, I give you OrmLite! … codeblock
OrmLite is extremely simple to use. Firstly, I added the ormlite-jdbc dependency to my Maven pom.xml.
I then created a ‘User’ model class to represent my users table. This contains three fields: the auto-incrementing id; a username; and e-mail address, all done with annotations:
package net.morgz.core.database;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
@DatabaseTable(tableName = "users")
public class User {
@DatabaseField(generatedId = true)
private int id;
@DatabaseField
private String username;
@DatabaseField
private String email;
public User() {
}
public int getId() {
return this.id;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Step 4 – MySQL connection
I now needed a connection to a MySQL database. I installed the mysql-connector dependency using Maven and added a few more lines to my Main class to instantiate the MySQL driver and set up the connection details:
String databaseUrl = "jdbc:mysql://localhost/spark";
ConnectionSource connectionSource = new JdbcConnectionSource(databaseUrl);
((JdbcConnectionSource)connectionSource).setUsername("spark");
((JdbcConnectionSource)connectionSource).setPassword("spark");
Now, to keep the code nice and clean, I’ve always used the Data Access Object pattern in Java. Much like the ‘Repository’ class in Doctrine for PHP, these classes adhere to the Single responsibility principle where the class should do one thing and one thing only. In this case, my DAO object should only perform operations on the user table. I was under the impression I’d have to create a DAO class from scratch but, OrmLite to the rescue again, it automatically created DAO objects for you:
Dao<User,String> userDao = DaoManager.createDao(connectionSource, User.class);
How awesome is that? 🙂
Step 5 – Creating the table
So, having a connection to the database and a DAO, I now needed to create my user table. For a quick win, I found that I could avoid migrations by using this neat little snippet:
TableUtils.createTableIfNotExists(connectionSource, User.class);
This line pretty much does what it says; it will create the users table if it doesn’t already exist.
Step 6 – RESTful POST request
Now I can go ahead and add some users via a RESTful POST request:
post(new Route("/users") {
@Override
public Object handle(Request request, Response response) {
String username = request.queryParams("username");
String email = request.queryParams("email");
User user = new User();
user.setUsername(username);
user.setEmail(email);
userDao.create(user);
response.status(201); }
});
With my Spark server running, if I fire a POST request to the following URL…
http://localhost:4567/users?username=jmorgan&email=jon.morgan@boxuk.com
…I see the 201 ‘Created’ status returned and, on checking the database, the user has been persisted with ID 1. Pretty damn slick!
Step 7 – DAO class
I can now go ahead and change my “GET user by id” method to use the DAO class:
get(new Route("/users/:id") {
@Override
public Object handle(Request request, Response response) {
User user = userDao.queryForId(request.params(":id"));
if (user != null) {
return "Username: " + user.getUsername(); } else {
response.status(404); return "User not found";
}
}
});
Step 8 – GET request
And if I now fire a GET request to:
http://localhost:4567/users/1
I see the username returned! 🙂
At Box UK we have a strong team of bespoke software consultants with more than two decades of bespoke software development experience. If you’re interested in finding out more about how we can help you, contact us on +44 (0)20 7439 1900 or email info@boxuk.com.