Friday, August 30, 2013

Spring Data, Mongo and Play 2.1

Ok we will go back in this post to Java and the idea for today is to integrate Mongo + Spring Data, with a great framework, called Play(version will be 2.1)

Of course, we talk about Spring, it means we start with some configurations...
Because we are working with play, please forget for a moment about Maven and we have two solutions for adding dependecies
1.Create a lib folder and add every jar you want
                              or
2.Update appDependencies from Project/Build.scala file in a Maven style
GroupArtifactVersion
"org.springframework""spring-core""3.2.2.RELEASE"

import sbt._
import Keys._
import play.Project._

object ApplicationBuild extends Build {

  val appName         = "MongoPlayExample"
  val appVersion      = "1.0-SNAPSHOT"

  val appDependencies = Seq(
    // Add your project dependencies here,
    "org.springframework" % "spring-core" % "3.2.2.RELEASE",
    "org.springframework" % "spring-context" % "3.2.2.RELEASE",
    "org.mongodb" % "mongo-java-driver" % "2.11.0",
    "org.springframework.data" % "spring-data-mongodb" % "1.2.0.RELEASE",
    "cglib" % "cglib" % "2.2.2",
    javaCore,
    javaJdbc,
    javaEbean
  )

  val main = play.Project(appName, appVersion, appDependencies).settings(
    // Add your own project settings here      
  )

}
Now because we don't really like today old Spring xml configurations, we have to create a SpringConfiguration class annotated with @ Configuration and a Global class for accessing ApplicationContext

 **Global.java
public class Global extends GlobalSettings{

    private static ApplicationContext applicationContext;

    @Override
    public void onStart(Application application) {
     System.out.println("on start");
        applicationContext = new AnnotationConfigApplicationContext(SpringConfiguration.class);
    }
    public static ApplicationContext getContext() {
        if (applicationContext == null) {
            throw new IllegalStateException("application context is not initialized");
        }
        return applicationContext;
    }
}
**SpringConfiguration.java
@Configuration
public class SpringConfiguration {
 
 public @Bean
 MongoDbFactory mongoDbFactory() throws Exception {
  return new SimpleMongoDbFactory(new MongoClient(), "PlayDB");
 }
 
 public @Bean(name="mongoTemplate")
 MongoTemplate mongoTemplate() throws Exception {
 
  MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory());

  return mongoTemplate;
 
 }
 
 public @Bean(name="repositoryUser")
 RepositoryUser repositoryUser() throws Exception
 {
  return new RepositoryUserImpl(mongoTemplate());
 }
}
As you can see we use some Spring Data features for connectiong to a Mongo Database and we define the beans in the code not in xml files.

After finishing the configuration part, the next step, is to create an entity(document) and a repository layer to show how to work with spring data mongo operations.

**User class
@Document(collection = "users")
public class User {
 
 @Id
 private String id;
 
 private String username;
 
 private String password;
 
 private String role;

 public User(String username, String password, String role) {
  super();
  this.username = username;
  this.password = password;
  this.role = role;
 }
       /*please implement getters and setters*/


**RepositoryUser interface
public interface RepositoryUser {

 List getAll();
 void save(User user);
 void delete(User user);
 User findById(String id);
}


**RepositoryUserImpl class
public class RepositoryUserImpl implements RepositoryUser {

 private MongoOperations mongoOperations;
 
 public RepositoryUserImpl(MongoOperations mongoOperations)
 {
  this.mongoOperations = mongoOperations;
 }
 @Override
 public List getAll() {
  // TODO Auto-generated method stub
  return mongoOperations.findAll(User.class);
 }

 @Override
 public void save(User user) {
  // TODO Auto-generated method stub
  mongoOperations.save(user);
 }

 @Override
 public void delete(User user) {
  // TODO Auto-generated method stub

 }

 @Override
 public User findById(String id) {
  // TODO Auto-generated method stub
  return null;
 }

}


Using Spring Data with Mongo offers the possibility to work with entities like any other ORM framework for relational databses like Hibernate for example...

** Controller for integrating our beans
public class Application extends Controller {
 
 private RepositoryUser repositoryUser=(RepositoryUser) Global.getContext().getBean("repositoryUser");
    
 public Result index() {
        //return ok(views.html.index.render("Your new application is ready."));
     //this.repositoryUser.save(new User("ionel", "abcd", "user"));
     return ok(this.repositoryUser.getAll().get(0).toString());
    }
  
}


And this is it! I created a short but strong example working with Spring Data, Mongo DB and Play Framework. In the future I hope we will come back to Play because it deserves many articles and a huge space in software development.I think Play can compete in the future with Wicket or Spring without any problems.Good luck! MVC, java, dependency injection, mongo, spring, spring data, play framework, play 2.1, play GlobalSettings

1 comment:

  1. same as i have done in spring data couchbase but its not getting a bean while running in play framework

    ReplyDelete