开发者

Using Morphia with Spring

开发者 https://www.devze.com 2023-02-18 17:08 出处:网络
The Google 开发者_StackOverflow中文版Code site of Morphia says it \"works great with Guice, Spring, and other DI frameworks.\"

The Google 开发者_StackOverflow中文版Code site of Morphia says it "works great with Guice, Spring, and other DI frameworks."

I'm learning Spring at the moment, so i'm just experimenting with connecting these two tools. I've created a User POJO to store user objects with Morphia in MongoDB. I've also created a UserDAO class extending BasicDAO from Morphia to access objects.

My Spring application context configuration XML looks like this:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"
           xmlns:aop="http://www.springframework.org/schema/aop">

      <bean class="java.lang.String" id="mongoDb">
        <constructor-arg value="test"/>
      </bean>

      <bean class="com.google.code.morphia.Morphia" id="morphia" />
      <bean class="com.mongodb.Mongo" id="mongo"/>
      <bean class="hu.inagy.testspring.daos.UserDAO" id="userDao">
        <constructor-arg ref="morphia" index="0" />
        <constructor-arg ref="mongo" index="1" />
        <constructor-arg ref="mongoDb" index="2" />
      </bean>

    </beans>

I have a simple main class to test functionality:

  public class App 
  {
      public static void main( String[] args )
      {
          ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/app-context.xml");
          UserDAO userDao = (UserDAO) applicationContext.getBean("userDao");

          userDao.deleteByQuery(userDao.createQuery());

          User user = new User();
          user.setName("Test");
          userDao.save(user);

          User ret = userDao.find().get();
          System.out.println("Saved user is: "+ret);
      }
  }

This works fine, however i don't know if i did everything as it should be. For example i haven't called ensureIndexes() and ensureCaps() on the datastore. My code also doesn't have an explicit mapping call for the POJOs on the Morphia object.

Are these done for me automatically or should i do other things to use Morphia correctly with Spring?


I don't use spring but this articles seems to talk about exactly what you need, a hook to do things when you app starts: http://leshazlewood.com/2007/07/30/spring-application-bootstrap-data/

You can do the Datastore.ensureIndexes/Caps() there.

You can also read this thread about using @Autowire and annotations instead of the xml, if you like that stuff.

http://groups.google.com/group/morphia/browse_thread/thread/1013b17963f29468

0

精彩评论

暂无评论...
验证码 换一张
取 消