Skip to content

Starting a DATABASE connection

Luiza Prestes edited this page Jul 22, 2021 · 1 revision

Using the API

To use the API, you should create a ConnectionFactory to access the database with the credentials. The connection is created between multiple properties, described below

Type: Type of the database
Hostname: Hostname of the database, only used for MySQL and PostgreSQL providers
Port: Port for the database access, used in MySQL and PostgreSQL providers
Database: Name of the database, used in MongoDB, MySQL and PostgreSQL providers
Username: Username for the database access, used in MongoDB, MySQL and PostgreSQL providers
Password: Password for the database access, used in MongoDB, MySQL and PostgreSQL providers
Path: Path where it will be stored, used in H2 and SQLite providers

Compatible names for the type property:

MongoDB - "MONGODB", "MONGO"
MySQL - "MYSQL"
POSTGRESQL - "POSTGRESQL", "POSTGRE", "POST", "GRE"
H2 - "H2"
SQLite - "SQLITE", "SQL", "LITE"

Alright! Now you already know what properties is used to create the connection and what properties each type of database uses, now let's check the ConnectionFactory example

@Getter
public class ConnectionFactory {

      private final Storage storage;

      public void start() {
        this.storage = StorageFactory.getInstance().startStorage(new PropertiesBuilder()
          .with("driver", "MongoDB")
          .with("username", "MONGO_USERNAME")
          .with("password", "MONGO_PASSWORD")
          .with("hostnane", "MONGO_HOSTNAME")
          .with("database", "MONGO_DATABASE")
        );
      }
}

After instanciating the ConnectionFactory, the connection will be created! Now, how do we create DAOs?

DAO

The databases API provides a default DAO for all databases, for MongoDB, we don't need to add any annotations, as the DAO has it's default methods.

The User object should always have a @Storable annotation in the class and a @Key annotation at the key to work with the DAO

private final StorageDao<User> dao;

public UserFactory(final Storage storage) throws DaoException {
    this.dao = storage.startDao(User.class);
}

After that, you have a perfectly working DAO for your Object, then it will get all information needed with the default database set on your connection factory.

Clone this wiki locally