#How can I add support for multiple databases?

1 messages ยท Page 1 of 1 (latest)

arctic saffron
#

This is confusing, so I'll explain.

My plugin uses MongoDB and I'm adding H2.
I need to figure out a way to switch between them according to the value of a YAML value (BoostedYAML/SnakeYAML)

Basically if a YAML value says MongoDB, then use the MongoDB database class, if it says H2, use the H2 database class

cedar sandBOT
#

<@&987246584574140416> please have a look, thanks.

cedar sandBOT
#

While you are waiting for getting help, here are some tips to improve your experience:

Code is much easier to read if posted with syntax highlighting and proper formatting.

If nobody is calling back, that usually means that your question was not well asked and hence nobody feels confident enough answering. Try to use your time to elaborate, provide details, context, more code, examples and maybe some screenshots. With enough info, someone knows the answer for sure.

Don't forget to close your thread using the command </help-thread close:1027500463647621170> when your question has been answered, thanks.

arctic saffron
#

Take note this is in Java.

arctic saffron
#

I'd also like to use this kind of system for other databases SQL or not

#

If you need to ask something do not hesitate to ๐Ÿ™‚

edgy cloak
#

You would create an interface for all database interactions, and write an implementation for each database you want to support

stray charm
#

use Hibernate and just set up multiple database connection configs

#

then just select a different config by some condition

arctic saffron
#

is there a way to alternate between the connections?

arctic saffron
arctic saffron
cedar sandBOT
arctic saffron
cedar sandBOT
edgy cloak
#
Database db = switch (database) {
  "h2" -> new H2Connector(),
  "sqlite" -> new SQLiteConnector(),
  "mongodb" -> new MongoDBConnector()
}```
#

something like this is what you'd use

#

to switch between implementations

#

(note that your code wouldn't work for nosql databases, even though you were talking about MongoDB in the first post, so that would at least need another layer of abstraction to work out ๐Ÿ˜› )

arctic saffron
#

"public class AbstractDatabaseHandler<T>"?

And then T would connect to the database by creating the connection via interface

edgy cloak
#

you'll basically need an interface with CRUD operations, and implement that interface per supported database type

#

as SQL shares a lot of common language, you might be able to abstract those into a subgroup (i.e. a simple select will likely be exactly the same in H2, SQLite, Mariadb, Postgres, OracleDB or MsSQL)

#

so start with java public interface Database<T> { void create(T entity); List<T> read(); void update(T entity); void delete(T entity); } of course, change the method signatures as you see fit, or add more methods where required

cedar sandBOT