Created
November 10, 2016 21:48
-
-
Save ethom7/a9af46187235fc743208269bbe2cd5f1 to your computer and use it in GitHub Desktop.
Using Jackson and Mongo Java Driver to insert and retrieve a POJO from the MongoDB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Person is a POJO, upload to db, retrieve from db | |
Person person = new Person(); | |
person.setName("Evan Thompson"); | |
person.setNickname("Unc"); | |
ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally | |
try { | |
String peep = mapper.writeValueAsString(person); | |
Document doc = Document.parse(peep); // this is what shortens the add to db | |
collection.insertOne(doc); | |
} catch (JsonProcessingException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
Bson filter = Filters.eq("name", "Evan Paul Leslie Thompson"); | |
Bson projections = Projections.exclude("_id"); | |
MongoCursor<Document> cur = collection.find().projection(projections).iterator(); | |
try { | |
while (cur.hasNext()) { | |
Document doc = cur.next(); | |
try { | |
Person pers = mapper.readValue(doc.toJson(), Person.class); | |
System.out.println(pers.getName()); | |
System.out.println(pers.getNickname()); | |
} catch (JsonParseException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} catch (JsonMappingException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} catch (IOException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
} | |
} | |
finally { | |
cur.close(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment