Searching...
Tuesday, 18 September 2012

Java Mongodb Morphia BasicDAO Example

23:31

Create a Maven project and add below dependencies

<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>org.mongodb.morphia</groupId>
<artifactId>morphia</artifactId>
<version>1.0.1</version>
</dependency>
</dependencies>
Create a  pojo class which includes the morphia annotaions
package com.vinod.examples;

import org.bson.types.ObjectId;
import org.mongodb.morphia.annotations.Entity;
import org.mongodb.morphia.annotations.Id;

@Entity(value = "Employee", noClassnameStored = true)
public class Employee {
@Id
private ObjectId id;
private String name;
private String address;

public ObjectId getId() {
return this.id;
}

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

public String getName() {
return this.name;
}

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

public String getAddress() {
return this.address;
}

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

@Override
public String toString() {
return "Employee [id=" + this.id + ", name=" + this.name + ",
address=" + this.address + "]";
}

}
Create a class using Morphia BasicDAO
package com.vinod.examples;

import java.util.List;

import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.dao.BasicDAO;

public class EmployeeDAO extends BasicDAO<Employee, String> {

public EmployeeDAO(Class<Employee> entityClass, Datastore ds) {
super(entityClass, ds);
}

public List<Employee> findAll() {
return ds.find(Employee.class).asList();
}

public List<Employee> findUnderName(String name) {
return ds.find(Employee.class).filter("name = ", name).order("name").asList();
}

}
Create a    Main class to test (Make sure that your local mongodb is up and running)
package com.vinod.examples;

import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Morphia;
import com.mongodb.MongoClient;

public class MorphiaBasicDAOTest {
public static final String DB_NAME = "mydb";

public static void main(String[] args) {
try {
Employee emp = new Employee();
emp.setName("vinod");
emp.setAddress("Bangalore");
MongoClient mongo = new MongoClient("127.0.0.1", 27017);
Datastore datastore = new Morphia().mapPackage("com.vinod.examples").createDatastore(mongo, DB_NAME);

EmployeeDAO empDoa = new EmployeeDAO(Employee.class, datastore);
empDoa.save(emp);
System.out.println("Employee Data saved");
System.out.println("All employees: " + empDoa.findAll());

} catch (Exception e) {
e.printStackTrace();
}

}

}
Output
Employee Data saved
All employees: [Employee [id=56897261f5d3c814db20c5de, name=vinod, address=Bangalore],
Employee [id=568972aef5d3c814ddb7a3d6, name=vinod, address=Bangalore],
Employee [id=56897d55f5d3c81553b10d46, name=vinod, address=Bangalore]]

0 comments: