How to save interfaces in Quarkus MongoDB with Panache?

35 Views Asked by At

I have an interface with multiple implementations. How can I save all the implementations to the same collection in MongoDB without manually configuring codecs. This is what I have done:

public interface Vehicle {
    Instant getTimestamp();
}

@MongoEntity(collection = "vehicles")
@BsonDiscriminator("Bicycle")
public class Bicycle implements Vehicle {
    private Instant timestamp;
    private String name;

    public Bicycle() {
    }
// getters and setters
}

@MongoEntity(collection = "vehicles")
@BsonDiscriminator("Car")
public class Car implements Vehicle {
    private Instant timestamp;
    private String color;

    public Car() {
    }
// getters and setters
}

@ApplicationScoped
public class VehicleRepository implements PanacheMongoRepository<Vehicle> {
}

Saving to the collection works fine, but when I do vehicleRepository.listAll() a CodecConfigurationException occurs:

Caused by: org.bson.codecs.configuration.CodecConfigurationException: An exception occurred when decoding using the AutomaticPojoCodec.
Decoding into a 'Vehicle' failed with the following exception:

Cannot find a public constructor for 'Vehicle'.  Please ensure the class has a public, empty constructor with no arguments, or else a constructor with a BsonCreator annotation

Can this be done with Panache, because I would like codecs and everything required to be automatically configured.

0

There are 0 best solutions below