MorphiaOrg / morphia

MongoDB object-document mapper in Java based on https://github.com/mongodb/mongo-java-driver
Apache License 2.0
1.65k stars 456 forks source link

How do I register a custom codec #2990

Open TrueReassembly opened 6 months ago

TrueReassembly commented 6 months ago

Please ask your question and provide whatever background or supporting information you think might be relevant:

I am currently trying to register a codec that I have created for the Bukkit ItemStack class but I cannot figure out how to register it. I have already looked at both MongoDB's and Morphia's documentation but was unable to find anything. Here is my Mongo Registration class

object MongoDatabase {
    lateinit var datastore: Datastore
    var connect by Delegates.notNull<Boolean>()

    fun init() {
        connect = false
        try {
            val mongoUri = ClickerServer.getInstance().config.getString("mongo.uri")
            if (mongoUri == null) {
                ClickerServer.getInstance().logger.severe("MongoDB URI not found in config.yml")
                ClickerServer.getInstance().server.pluginManager.disablePlugin(ClickerServer.getInstance())
                throw IllegalStateException("MongoDB URI not found in config.yml")
            }
            datastore = Morphia.createDatastore(MongoClients.create(mongoUri), ClickerServer.getInstance().config.getString("mongo.db")!!)
            datastore.mapper.config.packages(listOf("dev.reassembly.clickerserver.models"))
            // TODO: Register Codec here
            connect = true
        } catch (e: Exception) {
            connect = false
            e.printStackTrace()
        }

    }
}

Please complete the following information: Server Version: Unsure, I'm using mongo atlas if that's the question Driver Version: Whichever one comes bundled in morphia Morphia Version: 2.4.11

rdlf0 commented 5 months ago

You can try this:

final MongoClientSettings mongoClientSettings =
        MongoClientSettings.builder()
                ...
                other client settings
                ...
                .codecRegistry(
                        CodecRegistries.fromRegistries(
                                CodecRegistries.fromCodecs(new YourCodecClass()),
                                MongoClientSettings.getDefaultCodecRegistry()))
                .build();

final Datastore ds = Morphia.createDatastore(MongoClients.create(mongoClientSettings));