wfbarksdale
wfbarksdale

Reputation: 7606

Play 2.0 Morphia design pattern with mongodb

This is my first time using MongoDb and morphia and I am pretty new to databases in general. I am wondering how I should organize my code with morphia. I was looking into using a DAO like it says on the morphia documentation, but the way they seem to be doing it, I would have to create a DAO for each model object that I have. I liked play's methodology of basically giving Model objects the ability to save themselves but I only have vague notions of what is going on under the hood here, so I am not sure how to achieve this with morphia, or if it is even desirable to do so. The code I have so far looks like this for the skeleton of a User model.

@Entity("user")
public class User extends BasicDAO<User, ObjectId>{
    @Id ObjectId id;

public String firstName;

public String lastName;

public String email;

@Indexed public String username;

public String password;

public User(Mongo mongo, Morphia morphia){
    super(mongo, morphia, "UserDAO");
}
public User(){
    this(DBFactory.getMongo(), DBFactory.getMorphia());
}

public void save(){
    ds.save(this);
}

public static User findByUsername(String uname){
    return DBFactory.getDatastore().find(User.class, "username =", uname).get();
}

public static boolean authenticate(String uname, String pword){
    User user = DBFactory.getDatastore().createQuery(User.class).filter("username", uname).filter("password", pword).get();
    if(user == null)
        return false;
    else
        return true;
}
}

It is currently throwing a StackOverflowException, and I am not sure why, but is this a reasonable pattern to try to accomplish?

Also the DBFactory basically just exists to maintain the singleton mongodb connection.

Upvotes: 3

Views: 1891

Answers (2)

Karthik Sankar
Karthik Sankar

Reputation: 896

I started using Marphia with play framework 2.x. In my opinion, it is more sophisticated than the jackson mapper. I followed this example to install marphia plugin: https://github.com/czihong/playMongoDemo

Upvotes: 1

Ahmed Aswani
Ahmed Aswani

Reputation: 8659

Play 2.0 have a module for working with MongoDb I think You should give it a try https://github.com/vznet/play-mongo-jackson-mapper#readme

Upvotes: 2

Related Questions