Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Morphia with Java / GWT

I am trying to use MongoDB with Morphia as my back-end DB, I have implemented a utility class to simplify access to the database. I implemented basic add user function with However I am getting `lots of exceptions:

java.lang.IndexOutOfBoundsException exception when I put

Query query = datastore.createQuery(User.class).filter("name = ", username);

for checking user before comitting.

When removed: I get these two exceptions:

java.lang.RuntimeException: java.lang.NumberFormatException:

How to fix this issue?

Here are the code I have for the project:

MorphiaUtil.java:

public class MorphiaUtil {

    protected final Log log = LogFactory.getLog(getClass());
    private static Mongo mongo;
    private static Datastore datastore;

    static {
        try {
            // Create the database connection
            mongo =  new Mongo("localhost");
            datastore = new Morphia().createDatastore(mongo, "mygwtapp");
        } catch (UnknownHostException e) {
            System.err.println("Caught Unknown host exception:"+e);
            e.printStackTrace();
        } catch (MongoException e) {
            System.err.println("Initial Datastore creation failed:"+e);
            e.printStackTrace();
        }
    }

    public static Datastore getDatastore() {
        return datastore;
    }
}

UserServiceImpl.java

public class UserServiceImpl extends RemoteServiceServlet 
    implements UserService {
    @Override
    public void addUser(String username, String password)
            throws IllegalArgumentException {
        try {
            Datastore datastore = MorphiaUtil.getDatastore();
            Query query = datastore.createQuery(User.class).filter("name = ", username); 
            User user = (User) query.asList().get(0);
            if (user == null) {
                user = new User(username, password);
                datastore.save(user);
            }

        } catch (Exception e) { 
            System.err.print("Caught exception:"+e);
        }
    }
}
like image 668
quarks Avatar asked Nov 04 '22 18:11

quarks


1 Answers

I created a server version of all my beans, and before calling saving methods, i convert from Simple Beans (used in client side) to MorphiaBeans (used only for morphia operations).

That's not the best method to fix this issue, but works fine for me!

like image 173
Raduan Santos Avatar answered Nov 09 '22 11:11

Raduan Santos