Skip to content

Instantly share code, notes, and snippets.

@ashishtomer
Forked from JaiHirsch/GradesCodec.java
Created February 15, 2021 09:50
Show Gist options
  • Save ashishtomer/333fdbaa617232a0f4d2d145fc1ad92c to your computer and use it in GitHub Desktop.
Save ashishtomer/333fdbaa617232a0f4d2d145fc1ad92c to your computer and use it in GitHub Desktop.
MongoDB 3.0 java driver Codec example - Codec class for the mapping the Grades bean
package org.scratch;
import org.bson.BsonReader;
import org.bson.BsonString;
import org.bson.BsonValue;
import org.bson.BsonWriter;
import org.bson.Document;
import org.bson.codecs.Codec;
import org.bson.codecs.CollectibleCodec;
import org.bson.codecs.DecoderContext;
import org.bson.codecs.DocumentCodec;
import org.bson.codecs.EncoderContext;
import org.bson.types.ObjectId;
public class GradesCodec implements CollectibleCodec<Grades> {
private Codec<Document> documentCodec;
public GradesCodec() {
this.documentCodec = new DocumentCodec();
}
public GradesCodec(Codec<Document> codec) {
this.documentCodec = codec;
}
@Override
public void encode(BsonWriter writer, Grades value,
EncoderContext encoderContext) {
Document document = new Document();
ObjectId id = value.getId();
Double score = value.getScore();
Integer studentId = value.getStudentId();
String type = value.getType();
if (null != id) {
document.put("_id", id);
}
if (null != score) {
document.put("score", score);
}
if (null != studentId) {
document.put("student_id", studentId);
}
if (null != type) {
document.put("type", type);
}
documentCodec.encode(writer, document, encoderContext);
}
@Override
public Class<Grades> getEncoderClass() {
return Grades.class;
}
@Override
public Grades decode(BsonReader reader, DecoderContext decoderContext) {
Document document = documentCodec.decode(reader, decoderContext);
System.out.println("document "+document);
Grades grade = new Grades();
grade.setId(document.getObjectId("_id"));
grade.setStudentId(document.getInteger("student_id"));
grade.setType(document.getString("type"));
grade.setScore(document.getDouble("score"));
return grade;
}
@Override
public Grades generateIdIfAbsentFromDocument(Grades document) {
return documentHasId(document) ? document.withNewObjectId() : document;
}
@Override
public boolean documentHasId(Grades document) {
return null == document.getId();
}
@Override
public BsonValue getDocumentId(Grades document) {
if (!documentHasId(document))
{
throw new IllegalStateException("The document does not contain an _id");
}
return new BsonString(document.getId().toHexString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment