Searching...
Tuesday, 18 September 2012

Java Mongodb Morphia Connection and Simple save example

23:09

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 connection class using Morphia

package com.vinod.examples;

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

import com.mongodb.MongoClient;


public class MorphiaConnection {
private static final MorphiaConnection INSTANCE = new MorphiaConnection();

private final Datastore datastore;
public static final String DB_NAME = "mydb";

private MorphiaConnection() {
try {
MongoClient mongo = new MongoClient("127.0.0.1", 27017);
datastore = new Morphia().mapPackage( "com.vinod.examples").createDatastore(mongo, DB_NAME);
datastore.ensureIndexes();
} catch (Exception e) {
throw new RuntimeException(
"Error initializing mongo connections", e);
}
}

public static MorphiaConnection instance() {
return INSTANCE;
}

public Datastore getDatabase() {
return datastore;
}
}
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 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.query.Query;

public class MorphiaTest {

public static void main(String[] args) {
MorphiaConnection mc = MorphiaConnection.instance();
Datastore ds = mc.getDatabase();

Employee emp = new Employee();
emp.setName("vinod");
emp.setAddress("Bangalore");
ds.save(emp);
System.out.println("Employee details saved");

Query<Employee> emp1 = ds.find(Employee.class);

System.out.println(emp1.fetch().next());
}

}
Output
Employee details saved
Employee [id=56897261f5d3c814db20c5de, name=vinod, address=Bangalore]

0 comments: