Friday 14 November 2014

Storing POJOs in MongoDB Using Morphia

Storing POJOs in MongoDB Using Morphia:

Storing data in any Database is always a challenge irrespective of the Datadabase.

MongoDB is a leading NoSQL Database.
We create pojo/entity and store the data in the Database using framework like Hibernate.

Similarly we have Morphia which helps to store the data in the MongoDB.
In this we will try to store the Person data in the MongoDB.
Person will have name, address and the hobbies.

To store the above mentioned person data, we will create the entities.
Will create the entities for Person Entity, Hobbies Entity and the Address Entity.

We will embed the Hobbies and Address entity into Person.

Entity Annotation : To Store the class in MongoDB thro' Morphia, add annotate to class as @Entity

To Suppress the class name from the Mongo Document use "noClassnameStored=true".

@Id : Entity require unique @Id values; these values are stored in the MongoDB "_id" field.

@Indexed : This annotation applies an index to a field.
           The indexes are applied when the datastore.ensureIndexes() method is called

Example : @Indexed(value=IndexDirection.ASC, name="userName", unique=true, dropDups=true)

@Embedded :  to create a class that will be embedded in the Entity.

Below is the code sample of the mentioned Entities.

package com.mongo.morphia.entity;

import java.util.List;

import org.bson.types.ObjectId;

import com.google.code.morphia.annotations.Embedded;
import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Id;
import com.google.code.morphia.annotations.Property;

@Entity(noClassnameStored=true)
public class Person {

@Id
@Property("id")
private ObjectId id;

private String name;
private List<Hobbies> hobbies;
@Embedded
private Address address;

public ObjectId getId() {
return id;
}

public void setId(ObjectId id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public List<Hobbies> getHobbiess() {
return hobbies;
}

public void setHobbies(List<Hobbies> hobbies) {
this.hobbies = hobbies;
}

public Address getAddress() {
return address;
}

public void setAddress(Address address) {
this.address = address;
}

}


package com.mongo.morphia.entity;

import com.google.code.morphia.annotations.Embedded;

@Embedded
public class Address {
private String number;
private String street;
private String town;
private String postcode;

public String getNumber() {
return number;
}

public void setNumber(String number) {
this.number = number;
}

public String getStreet() {
return street;
}

public void setStreet(String street) {
this.street = street;
}

public String getTown() {
return town;
}

public void setTown(String town) {
this.town = town;
}

public String getPostcode() {
return postcode;
}

public void setPostcode(String postcode) {
this.postcode = postcode;
}

}



package com.mongo.morphia.entity;

import org.bson.types.ObjectId;

import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Id;
import com.google.code.morphia.annotations.Property;

@Entity
public class Hobbies {

@Id
@Property("id")
private ObjectId id;

private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public ObjectId getId() {
return id;
}

public void setId(ObjectId id) {
this.id = id;
}
}
DAO class..

package com.mongo.morphia.dao;

import com.google.code.morphia.Morphia;
import com.google.code.morphia.dao.BasicDAO;
import com.mongo.morphia.entity.Person;
import com.mongodb.Mongo;

public class PersonDAO extends BasicDAO<Person, String> {  

public PersonDAO(Morphia morphia, Mongo mongo, String dbName) {      
super(mongo, morphia, dbName);  
}
 
}





In the below class we have called the save , update , find and Delete operation. here we are using the entities to do all the operations.

package com.mongo.morphia;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
import com.google.code.morphia.mapping.Mapper;
import com.google.code.morphia.query.Query;
import com.google.code.morphia.query.QueryResults;
import com.google.code.morphia.query.UpdateOperations;
import com.mongo.morphia.dao.PersonDAO;
import com.mongo.morphia.entity.Hobbies;
import com.mongo.morphia.entity.Address;
import com.mongo.morphia.entity.Person;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

public class Example {

public static void main(String[] args) throws UnknownHostException,MongoException {

String dbName = new String("User");
Mongo mongo = new Mongo();
Morphia morphia = new Morphia();
Datastore datastore = morphia.createDatastore(mongo, dbName);

morphia.mapPackage("com.mongo.morphia.entity");

Address address = new Address();
address.setNumber("Q-101");
address.setStreet("M.G. Road");
address.setTown("Pune");
address.setPostcode("411001");

Hobbies hobbies = new Hobbies();
hobbies.setName("Trekking");

List<Hobbies> listHobbies = new ArrayList<Hobbies>();
listHobbies.add(hobbies);

Person person = new Person();
person.setAddress(address);
person.setName("Mr Martin d'souza");
person.setHobbies(listHobbies);

//Save Methods
PersonDAO personDAO = new PersonDAO(morphia, mongo, dbName);
personDAO.save(person);

//Find Methods
//use in a loop
for(Person personObj : datastore.find(Person.class, "hobbies.name", "Trekking")) {
System.out.println(personObj.getName());
}

//get back as a list
//List<Person> personObj1 = datastore.find(Person.class, "name", "Martin").asList();

// Get the Data Using Query Criteria
Query<Person> query = datastore.createQuery(Person.class);
query.and(query.criteria("hobbies.name").equal("Trekking"),
query.criteria("address.number").equal("Q-101"),
query.criteria("name").contains("Martin"));

QueryResults<Person> retrievedPersons = personDAO.find(query);

for (Person retrievedPerson : retrievedPersons) {
System.out.println(retrievedPerson.getName());
System.out.println(retrievedPerson.getAddress().getPostcode());
System.out.println(retrievedPerson.getHobbiess().get(0).getName());
}

//Update Methods
for (Person retrievedPerson : retrievedPersons) {

UpdateOperations<Person> updatePerson = datastore.createUpdateOperations(Person.class).set("name", "Kevin Gibbs");
datastore.update(datastore.createQuery(Person.class).field(Mapper.ID_KEY).equal(retrievedPerson.getId()), updatePerson);

//Delete Methods
//personDAO.delete(retrievedCustomer);
}
}

}

Thursday 13 November 2014

Java To Python.......

Learning a new thing is always a fun... then whatever it is ... you enjoy it...
I am learning Python now...I knew java and use it for building the application as of now....
While learning the Python, it doesn't seems to hard with respect to the syntax..its very easy..
its like plain text sort of thing being learnt...

Python's simple and straight-forward syntax also encourages good programming habbits, especially through its focus on white space indentation, which contributes to the development of neat looking code.

We try to put out some difference between Python and Java...

Before that I am not criticizing any language here, just wanted you to enjoy this as I had...

1. If you want to print the "Hello World" in java, it looks something like this

public class TestJava {
public static void main(String[] args) {

System.out.println("Hello World");
}
}

and the same thing in Python is

print "Hello, Python!";


2. When it comes to some reserved words ..then yes both the languages has some keys reserved. I dint find any difference here. And the view is same that the reserved words not be used as constant or variable or any other identifier names.


3. Next is line and indentation where In Python the fact is that there are no braces to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly enforced.

The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount.
Both blocks in this example are fine:

if True:
    print "True"
else:
  print "False"

and the below block in this example will generate an error:

if True:
    print "Answer"
    print "True"
else:
    print "Answer"
  print "False"


Thus, in Python all the continuous lines indented with similar number of spaces would form a block.


4. Quotation in Python: Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the same type of quote starts and ends the string.

Same is not the case with Java while defining the String literals.. :)

5. Commenting the code in Python : A hash sign (#) that is not inside a string literal begins a comment.
All characters after the # and up to the physical line end are part of the comment and the Python interpreter ignores them.

In java Single line commenting is done by "//" and multiple lines commenting is by /* */. Anything that comes between /* */ will be ignored.

6. Values Assigning to Variable : In Python
   count = 100  # integer assignment
   distance = 10.5 # floating
   name = "Steve"  # String

   In Java

   String name = "xyx";
   Integer count = 100;

   Difference is you need to mention the data type along with the variable name.

7. Multiple Assignment:
   Python allows you to assign a single value to several variables simultaneously.
   For example:
a = b = c = 1

   Same thing is not possible in Java.

   You can also assign multiple objects to multiple variables.
   For example:
  a, b, c = 1, 2, "john"
   and if you print it the output is
   print a,b,c
   1 2 john

8. Lists : Lists are the most versatile of Python's compound data types.
   A list contains items separated by commas and enclosed within square brackets ([]).

   In java you have different collections like ArrayList and Hashset etc.

   One difference between them is that all the items belonging to a list in Python can be of different data    type.

   In Java it does too but seems hard when you introduce Generics.

9. Value access from List :
   In Python the values stored in a list can be accessed using the slice operator ( [ ] and [ : ] ) with
   indexes starting at 0 in the beginning of the list and working their way to end -1.
   list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
   
   print list          # Prints complete list
   print list[0]       # Prints first element of the list
   print list[1:3]     # Prints elements starting from 2nd till 3rd

   In Java use of Iterator or new for each would be used to get the data.

10. Defining a Function
    Here are simple rules to define a function in Python.
    Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
    Any input parameters or arguments should be placed within these parentheses. You can also define       parameters inside these parentheses.
    The first statement of a function can be an optional statement - the documentation string of the               function or docstring.
    The code block within every function starts with a colon (:) and is indented.
    The statement return [expression] exits a function, optionally passing back an expression to the caller.
    A return statement with no arguments is the same as return None.
   
    For Example :
    def printme( str ):
    "This prints a passed string into this function"
    print str
    return

    In Java :
    public void test(Integer i){
System.out.println("funtion" + i);
    }


I would appreciate if anyone add more if they knew and correct me if I am wrong at any point...
Till then cheers...