Converting DBObject to a POJO using MongoDB Java - java

I'm a starting to use MongoDb and developping a small web application that connect to this Mongo Database.
I have a DAO with a method to find a user from the db according to the email address assigned to the user. Each user should have a unique email address so I can assume I'll get only one document. How can then convert the DBObject to a User entity?
Here my code:
#Override
public User findUserByEmailAddress(String email) {
DB db=MongoHelper.getDb();
BasicDBObject query = new BasicDBObject();
query.put("email", email);
DBCollection users=db.getCollection("users");
DBCursor cursor = users.find(query);
DBObject user=cursor.next();
//Code to convert the DBObject to a User and return the User
}
Thank you very much in advance!

DBObject is a map, so you can get required values by simply accessing it by corresponding key.
For example:
DBObject query = QueryBuilder.start("email").is(email).get();
DBCursor cursor = users.find(query);
while (cursor.hasNext()) {
DBObject user = cursor.next();
String firstName = (String)user.get("first_name");
String lastName = (String)user.get("last_name");
//TODO: use extracted properties to build User object
}
Note that depending on document structure, the returned property can be itself a map. So appropriate casting is required. In addition, I would not assume there can be only one email per user in the document database (due to errors, wrong input etc). It should be enforced on the application level.

Related

how to get distinct values from mongodb through java with specific condition

i am trying to get distinct values from mongodb with java
in particular unique id but i dont found this .
DB database = MongoConnection.getInstance();
DBCollection collection = database.getCollection("licence_entery_fl3_fl1");
BasicDBObject wheremap = new BasicDBObject();
wheremap.put("int_distillery_id", act.getDist_id());
wheremap.put("vch_licence_type", act.getVch_to());
wheremap.put("vch_lic_unit_type", "D");
DBCursor cursor = collection.find(wheremap);
Iterator<DBObject> itr = cursor.iterator();
log.info("Fetching all documents from the collection licence_entery_fl3_fl1 ---------"+itr);
while(itr.hasNext()){
DBObject record = itr.next();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
Mongo_GatepassToWholesale_20_21_Model model = mapper.readValue(record.toString(), Mongo_GatepassToWholesale_20_21_Model.class);
System.out.println("--licence_nmbr.--"+model.licence_nmbr+"---");
item.setValue(model.vch_licence_no);
item.setLabel(model.licence_nmbr);
list.add(item);
}
this is implement for jsf .
please help me
I think the easiest way is to use spring data as an ORM with a specific datasource, so you can go through criteria like the following using regex :
Query query = new Query();
query.addCriteria(Criteria.where("name").regex("^A"));
List<User> users = mongoTemplate.find(query,User.class);
or to have a select by identifier only used the MongoRepository interface by a findDistinctById() as ou can see here -- see chapter 6.3. Query methods --

Use Of $slice Query while fetching data from mongodb in JAVA

I have a small query which is giving the result while invoking it on mongo database. But when I am using this in JAVA for fetching the data then it giving me exception.
Below is the query :
db.collectionName.find({'name': 'Sam'},{"Address": { "$slice": -1 } })
In database, name is the key and address is the list containing lets say 4 number of addresses.We want to fetch the updated address in "Address" KEY.
Below is the java code which we are using :
final DBCollection dbCollection = mongoTemplate.getCollection("apMonitoringData");
final BasicDBObject query = new BasicDBObject();
query.put("name", "sam");
query.put("address", new BasicDBObject("$slice", -1));
final BasicDBObject sortQuery = new BasicDBObject();
// Sorting in Descending order for last updated entry
sortQuery.put("_id", -1);
final DBCursor dbCursor = dbCollection.find(query).sort(sortQuery).limit(1);
DBObject dbObject = null;
while (dbCursor.hasNext()) {
dbObject = dbCursor.next();
}
return dbObject;
but it is giving error as
com.mongodb.MongoException: Can't canonicalize query: BadValue: unknown operator: $slice
Can anybody please look into this.
You will need to separate the query from the fields.
Also, use append when you want to add entries to a document instead of put
BasicDBObject query = new BasicDBObject("name","sam");
BasicDBObject fields = new BasicDBObject("address",new BasicDBObject("$slice", -1));
collection.find(query,fields).sort(sortQuery).limit(1);

return atribute of an object in mongoDB using java

I am using for first time MongoDB with Java. I think it is an easy question but I am not finding the answer.
I have a collection of users, with the next atributes: username, pass and name.
I want to save in a String the value of the password, by specifying the username.
for example: I have a user {"username":"UserName", "pass":"abc", "name":"Us"}
I want to save the value abc on a String.
I have tried with the next code, but I am not specifying which is the user of the password that I want.
DBCollection table = db.getCollection("user");
DBObject us= table.findOne();
String pass = (String) us.get("pass");
System.out.println(pass);
thanks for the help
findOne can take a query. See findOne(DBObject query)
DBObject query = new BasicDBObject("username", "test");
DBObject us = table.findOne(query);
//username must be unique to fetch one row
DBObject query = new BasicDBObject("username","myName");
DBObject us = table.findOne(query);
DBCursor cur = collection.find(us);
String pass= null ;
while(cur.hasNext()){
pass= cur.next().toString();
}
cur.close();
JSONObject json = new JSONObject(pass);
String thePass= json.getString("pass");

How to get the _id of one document MongoDB Java

I'm using MongoDB and Java-driver.
I need to insert a document into MongoDB and retrieve the _id of this document. The insert method return a [WriteResult][1].
I don't know how I have to use the WriteResult object to retrieve the _id, because I try to do this:
public void insertDocument(BasicDBObject fact){
DBCollection coll = this.getCollection("facts");
WriteResult result = coll.insert(fact);
String id = (String) result.getField("_id");
System.out.println("--------------------------->"+id);
}
And I have a null String in the println.
My question is how I can get the entire object (with _id) that I just inserted into the database.
Thanks!
After the BasicDBObject instance is inserted, the MongoDB driver modifies the instance in the terms of setting a value to the _id field (if you haven't specified such).
Therefore, you can still use the fact object and get the _id from there:
System.out.println(fact.get("_id"));

Using Spring Hibernate getHibernateTemplate().find to to select columns

I am using
List<USERS> user =
getHibernateTemplate().find("select uid, username,email from USERS");
to get three columns values from the users TABLE. But I can access no individual column value using the "user" object because the "user" type is an object type and I can't cast it to the USERS.
Is there any ways to use the "user" object and access individual columns value?
Why are you just querying selected columns - just get the whole row(s). Let me know if that helps.
If you are fetching only few columns, the hibernate template will return a list of object arrays.
Your example should look like this,
List<Object[]> userDetails =
getHibernateTemplate().find("select uid, username,email from USERS");
And you should know the first element is a integer and second, third are string and do cast on your own. This is very error prone ofcourse.
Thanks Nilesh and Sean for your suggestions. I always deal with the objects instead of individual columns. But this specific app works with other tables from another app which is not written in Java (That is why I am using USERS table not "User", because it is already created by another app) and is not using hibernate. I created a USERS class that implements UserDetails and has much less columns than the original app USERS table. When I get the whole object I get a formatting error that is why I tried using selected columns instead of the object.Anyhow I wrote this code and was able to get the individual columns:
List user=
getHibernateTemplate().find("select uid, username,email from USERS where uid<>0 AND obj_type=1");
List<USERS> l = new ArrayList<USERS>();
for (int i = 0; i < user.size(); i++) {
USERS du = new USERS();
Object[] obj = (Object[]) user.get(i);
Integer uid = (Integer) obj[0];
du.setUid(uid);
String username = (String) obj[1];
du.setUsername(username);
String email = (String) obj[2];
du.setEmail(email);
l.add(du);
}
My last question: isn't it more expensive to get the whole columns(the object) than getting the individuals ones?
Keep in mind it that...
getHibernateTemplate.find() method returns List of based on passed object.
Then after this you have to take List of Users then you have to separate all resulting object and after specified a object you can access attribute of it.
Its very easy..
If you have any query then tell me
I will try my best.
#Override
public Object findByNo(Object id) throws Exception {
List list = getHibernateTemplate().find(
"select book from Book book " +
"where book.id=?",id);
if (list.size() != 0) {
return list.get(0);
} else {
return new Book();
}
}
I'm guessing your db table is called USERS and the entity class is called User. If that is the case, then you should do something like this:
List<User> users = getHibernateTemplate().find("from User");
for(User user: users){
// you probably don't need the id, so I'll skip that
String email = user.getEmail();
String userName = user.getUserName();
// now do something with username and email address
}
If you use an ORM framework, deal with objects, not with Database Columns!
And about naming:
Java naming conventions suggest that a class name is in TitleCase (or more precisely UpperCamelCase), not UPPERCASE. Also, a class that represents a single user should be called User, not Users.
you can try something like this:
for (TemplateAttributes templateAttributes1 : templateAttributes) {
templateAttributes1.setTemplates(templates);
templateAttributes1.setCreateDate(new Date());
templateAttributes1.setCreateUser(ApplicationConstants.userName);
templateAttributes1.setLastModified(new Timestamp(new Date().getTime()));
templateAttributesNew.add(templateAttributes1);
}
templates.setTemplateAttributes(templateAttributesNew);
templates.setUpdateDate(new Date());
templates.setUpdateUser(ApplicationConstants.userName);
templates.setLastModified(new Timestamp(new Date().getTime()));
getHibernateTemplate().bulkUpdate("delete from TemplateAttributes where templateAttributePK.templates.id="+templates.getId());
getHibernateTemplate().update(templates);
Try this
List<USERS> user =(List<USERS>)(List<?>)
getHibernateTemplate().find("select uid, username,email from USERS");

Categories

Resources