A java mongoDB utility
- Installing
- Getting Started
- Basic saving & loading
- Serializing Complex objects
- Excluding a variable from serialization
Maven
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories> <dependency>
<groupId>com.github.Lickymoo</groupId>
<artifactId>MongoHook</artifactId>
<version>LATEST-VERSION</version>
</dependency>Grade
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
dependencies {
implementation 'com.github.Lickymoo:MongoHook:LATEST-VERSION'
}
To get started simply create a new MongoHook class
MongoHook mongo = new MongoHook(new Host("1.1.1.1", 27017));You can connect multiple hosts like so:
MongoHook mongo = new MongoHook(new Host("1.1.1.1", 27017), new Host("2.2.2.2", 27017));Authentication can be done inline
MongoHook mongo = new MongoHook(new Host("1.1.1.1", 27017).withAuth("USER", "PASSWORD", "DATABASE"));After we have connected a our client we want to start the hook and connect our database and collection
mongo.start();
mongo.setDatabase("test_db");
mongo.setCollection("test_coll");
OR
mongo.start().setDatabase("test_db").setCollection("test_coll");MongoHook supports saving & loading for both entire classes & single variables
mongoHook.saveObject(ID, MyObject);//Serach by ID
MyObject myObject = mongoHook.getObjectById(ID, MyObject.class);
OR
//Alternatively, Search by value of element
MyObject myObject = mongoHook.getObject(VALUE, COLUMN NAME, MyObject.class);mongoHook.saveValue(ID, COLUMN NAME, VALUE);String myVar = mongoHook.getValue(ID, COLUMN NAME, String.class);
MyObject myObject = mongoHook.getValue(ID, COLUMN NAME, MyObject.class);By default, MongoHook uses Gson to serialize objects, so in theory, you do not need to use a serializer.
However, in the case of needing to save data in a different format or Gson not supporting your codec, MongoHook provides the VariableSerializer interface
public class MyClassToBeSaved{
int myInt;
@Serializer(MyObjectSerializer.class) MyObject;
}public class MyObjectSerializer implements VariableSerializer<MyObject>{
@Override
public String serialize(MyObject obj) {
//Serialize
}
@Override
public MyObject deserialize(String str) {
//Deserialize
}
}MongoHook will automatically serialize this through the VariableSerializer class
To exclude a variable from being serialized, simply add the @Exclude annotation
public class MyClassToBeSaved{
int myInt;
@Exclude MyObject;
}