Type Handler
Type handlers are applied to entity class fields for assignment and conversion.
Note
- For example, if the field type is
InputStream, the content needs to be converted tobyte[]for storage, and when querying, theBinaryclass returned by MongoDB should be converted back toInputStream. - Type handlers have higher priority than converters and mappers because
TypeHandleroperates at the field level. - When using a type handler on an entity class, you need to implement two methods of the type handler. If it returns
null, MongoPlus processing continues; otherwise, the data returned by the type handler's methods is used directly. - Pass the type handler through the
typeHandlerproperty of theCollectionFieldannotation on the entity class field, e.g.,@CollectionField(typeHandler = InputStreamTypeHandler.class).
com.mongoplus.handlers.TypeHandler
- This interface defines a type handler. All type handlers should implement this interface and its methods.
setParameter: Sets the value.getResult: Retrieves the result.
Example
First, implement the TypeHandler interface in your type handler class and set the generic type to the field type. Pass it via the typeHandler property of the CollectionField annotation.
java
// Example using InputStream
public class InputStreamHandler implements TypeHandler<InputStream> {}Next, implement the mapping methods of the TypeHandler interface to define the mapping strategy.
java
public class InputStreamHandler implements TypeHandler<InputStream> {
@Override
public Object setParameter(String fieldName, InputStream obj) {
try(ByteArrayOutputStream bos = new ByteArrayOutputStream()){
byte[] b = new byte[1024];
int len;
while ((len = obj.read(b)) != -1) {
bos.write(b, 0, len);
}
// Convert InputStream to byte[] and return
return bos.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public InputStream getResult(Object obj) {
// After setParameter, the retrieved data will be of type Binary
// Cast to Binary, get byte[], then convert to InputStream
return new ByteArrayInputStream(((Binary)obj).getData());
}
}Finally, apply it in the entity class.
java
@CollectionName(value = "user")
public class User {
@ID(type = IdTypeEnum.ASSIGN_ID)
private String userId;
@CollectionField(typeHandler = InputStreamHandler.class) // Set the typeHandler property and pass in our custom type handler
private InputStream file;
}
