遵循此https://docs.datastax.com/en/developer/java-driver/3.2/manual/object_mapper/custom_codecs/和this 我为这个类编写了自己的自定义编解码器,这是我的键空间中的用户类型
public class Condition{
BigDecimal value;
LocalDate validFrom;
LocalDate validUntil;
Set<Integer> ids;
}
如果我手动注册它,它会工作,但我想像示例中那样注释列:
@Column(codec = MyCustomDateCodec.class)
private MyCustomDate birth;
只有在我的自定义编解码器实现中有一个no-args构造函数时,这才有效。
问题是我不知道怎么写没有args构造函数。
我的自定义编解码器:
import com.datastax.driver.core.ProtocolVersion;
import com.datastax.driver.core.TypeCodec;
import com.datastax.driver.core.UDTValue;
import com.datastax.driver.core.UserType;
import com.datastax.driver.core.exceptions.InvalidTypeException;
import com.datastax.driver.extras.codecs.jdk8.LocalDateCodec;
import java.nio.ByteBuffer;
public class ConditionCodec extends TypeCodec<Condition> {
private TypeCodec<UDTValue> innerCodec;
private UserType userType;
public ConditionCodec(TypeCodec<UDTValue> innerCodec, Class<Condition> javaType) {
super(innerCodec.getCqlType(), javaType);
this.innerCodec = innerCodec;
this.userType = (UserType) innerCodec.getCqlType();
}
@Override
public ByteBuffer serialize(Condition condition, ProtocolVersion protocolVersion) throws InvalidTypeException {
return innerCodec.serialize(toUDTValue(condition), protocolVersion);
}
@Override
public Condition deserialize(ByteBuffer byteBuffer, ProtocolVersion protocolVersion) throws InvalidTypeException {
return toCondition(innerCodec.deserialize(byteBuffer, protocolVersion));
}
@Override
public Condition parse(String value) throws InvalidTypeException {
return value == null || value.isEmpty() || value.equals(null) ? null : toCondition(innerCodec.parse(value));
}
@Override
public String format(Condition value) throws InvalidTypeException {
return value == null ? null : innerCodec.format(toUDTValue(value));
}
protected Condition toCondition(UDTValue value) {
return value == null ? null
: new Condition(value.getDecimal("value"), value.get("validFrom", LocalDateCodec.instance),
value.get("validUntil", LocalDateCodec.instance), value.getSet("storeIds", Integer.class));
}
protected UDTValue toUDTValue(Condition value) {
return value == null ? null
: userType.newValue().setDecimal("value", value.getValue())
.set("validFrom", value.getValidFrom(), LocalDateCodec.instance)
.set("validUntil", value.getValidFrom(), LocalDateCodec.instance).setSet("storeIds", value.getStoreIds());
}
}