Interacting with the Database

Introduction

This is a large section that will cover how to interact with the database and safely get the data. It will show you how to get data asynchronously using the provided completable futures and walk you through basic methods even if you've never used them before.

Getting the Database Access Object (DAO)

To interact with our database we need the object that allows us to access the database. This is done by the following

MailMeAPI api;
PlayerMailDAO dao = api.getPlayerMailDAO();

CompletableFutures

The majority of the database methods use completable futures and this section will explain basic usages. Otherwise, try to look up usage.

CompletableFuture#thenApply

For the majority of access, this is what you will be using. If you haven't gathered, this data is asynchronous (off thread). So, it will complete later on to your code execution - hence the name. Something to note, is that the code inside is only ever executed whenever the method returns the variable. This could be 10 nano seconds later or 10 seconds later. Its usage is as follows

// Be aware your code is not always on the main thread when this block runs
future.thenApply(variable -> { /* code to run once variable is returned */ });

CompletableFuture#get

Since completablefuture is ran asynchronously by default, the rest of your code can run while it executes. But there may be instances where you simply need the variable before you execute any more code. Please note that this is a thread blocking operation. So a minecraft server would halt until it's finished execution. Its usage is as follows

future.get();

Getting Player Mail

The method and speed at which you get player mail is actually very dependent on the method you use and the database type in use. For example; MySQL supports querying with clauses. Long story short, we can get all the data and process on the sql server with conditions - without checking and getting the entire database like we would with json.

So it's important you use the correct methods for your use case.

Will retrieve all mail the provided UUID owns if any. The Mail Array with be EMPTY if the player has no mail or an error occurs. Console will be logged if an error occurs (in debug mode)

PlayerMailDAO dao = api.getPlayerMailDAO();
dao.getAllMail().thenAccept(mail -> {
    // Your code, remember this may not be the main thread.
});

Will retrieve all the mail the provided UUID has not read yet.

PlayerMailDAO dao = api.getPlayerMailDAO();
dao.getUnreadMail().thenAccept(mail -> {
    // Your code, remember this may not be the main thread.
});

Last updated