Skip to content

Database integration without leaving the class

Daniel edited this page May 3, 2024 · 1 revision

To work with an SQL database, ORMLite is used, so familiarize yourself with their documentation. However, there are a few important changes. First, we need to create a class for the object we want to store in the database, here without changes, everything as ORMLite dictates.

@DatabaseTable(tableName = "player_uuids")
public class PlayerUUID {
    @DatabaseField(generatedId = true, canBeNull = false, dataType = DataType.UUID)
    private UUID uuid;
    @DatabaseField(canBeNull = false, columnName = "player_name")
    private String playerName;
}

Now we need to create a repository that will manage our table as shown in the example.

@Component
public class PlayerUUIDRepository extends MySQLRepository<PlayerUUID/*our data type*/, UUID /*our data id type*/> /*or you can use any repository from dev.ckateptb.minecraft.jyraf.database.repository*/ {
    public PlayerUUIDRepository(String url, String username, String password) {
        super(url, username, password);
    }
}

After that, by accessing our repository, we can perform various operations such as save, find, delete, etc. To extend the functionality, you can refer to the repository#dao.

To serialize a type for SQL, you need to create a component that implements dev.ckateptb.minecraft.jyraf.internal.ormlite.field.DataPersister. Here's an example from Jyraf.

@Component
public class LocalDateTimeType extends LongType {

    public LocalDateTimeType() {
        super(SqlType.LONG, new Class<?>[]{LocalDateTime.class});
    }

    @Override
    public Object sqlArgToJava(FieldType fieldType, Object sqlArg, int columnPos) throws SQLException {
        long value = (Long) super.sqlArgToJava(fieldType, sqlArg, columnPos);
        return LocalDateTime.ofInstant(Instant.ofEpochMilli(value), ZoneId.systemDefault());
    }

    @Override
    public Object javaToSqlArg(FieldType fieldType, Object object) {
        LocalDateTime localDateTime = (LocalDateTime) object;
        return ZonedDateTime.of(localDateTime, ZoneId.systemDefault()).toInstant().toEpochMilli();
    }
}

For NoSQL databases (such as MongoDB), everything happens identically, except for serialization. NoSQL picks up serialization from SpongePowered/Configurate, as mentioned earlier and will be further explained.

Clone this wiki locally