NoSQL专题

MongoDB + Morphia使用

  环境: jdk 7, Eclipse (STS) 和 Maven 3 

首先下载MongoDB 然后运行。

用Maven准备一个Java 项目,codeRepo\MavenCommands.bat:

ECHO OFF

REM =============================
REM Set the env. variables.
REM =============================
SET PATH=%PATH%;C:\ProgramFiles\apache-maven-3.0.3\bin;
SET JAVA_HOME=C:\ProgramFiles\Java\jdk1.7.0

REM =============================
REM Create a simple java application.
REM =============================
call mvn archetype:create ^
       -DarchetypeGroupId=org.apache.maven.archetypes ^
       -DgroupId=org.academy ^
       -DartifactId=dbLayer002

pause

将项目目录导入到Eclipse即可,用Maven编译和运行:

mvn -e clean install.

下面开始编码,假设有一个实体: /dbLayer002/src/main/java/org/academy/entity/Person.java

package org.academy.entity;

public class Person {
       private String fname;

       [...]
}

准备一下maven的依赖: /dbLayer002/pom.xml

[...]
<!-- MongDB java driver to hook up to MongoDB server -->
<dependency>
       <groupId>org.mongodb</groupId>
       <artifactId>mongo-java-driver</artifactId>
       <version>2.7.3</version>
</dependency>
[...]

准备一下连接MongoDB的工具类:File: /dbLayer002/src/main/java/org/academy/util/MongoUtil.java

public class MongoUtil {

       private final static Logger logger = LoggerFactory
                       .getLogger(MongoUtil.class);

       private static final int port = 27017;
       private static final String host = "localhost";
       private static Mongo mongo = null;

       public static Mongo getMongo() {
               if (mongo == null) {
                       try {
                               mongo = new Mongo(host, port);
                               logger.debug("New Mongo created with [" + host + "] and ["
                                               + port + "]");
                       } catch (UnknownHostException | MongoException e) {
                               logger.error(e.getMessage());
                       }
               }
               return mongo;
       }
}

加入日志辅助调试:/dbLayer002/pom.xml

[...]
<slf4j.version>1.6.1</slf4j.version>
[...]
<!-- Logging -->
<dependency>
       <groupId>org.slf4j</groupId>
       <artifactId>slf4j-api</artifactId>
       <version>${slf4j.version}</version>
</dependency>
<dependency>
       <groupId>org.slf4j</groupId>
       <artifactId>jcl-over-slf4j</artifactId>
       <version>${slf4j.version}</version>
       <scope>runtime</scope>
</dependency>
<dependency>
       <groupId>org.slf4j</groupId>
       <artifactId>slf4j-log4j12</artifactId>
       <version>${slf4j.version}</version>
       <scope>runtime</scope>
</dependency> 

配置一下/dbLayer002/src/java/resources/log4j.properties

# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG, A1

# configure A1 to spit out data in console
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d [%t] %-5p %c - %m%n

 

这里要引入Morphia ,是一个Java对象和MongoDB转换工具,适合有JPA 经验的程序员。

配置Morphia依赖File: /dbLayer002/pom.xml

[...]
<!-- Required for Morphia -->
<repositories>
       <repository>
               <id>Morphia repository</id>
               <url>http://morphia.googlecode.com/svn/mavenrepo/</url>
       </repository>
</repositories>
[...]
<!-- Morphia - ORM for MongoDB -->
<dependency>
       <groupId>com.google.code.morphia</groupId>
       <artifactId>morphia</artifactId>
       <version>0.98</version>
</dependency>                                

下面是可选:

<dependency>
       <groupId>cglib</groupId>
       <artifactId>cglib-nodep</artifactId>
       <version>[2.1_3,)</version>
       <type>jar</type>
       <optional>true</optional>
</dependency>
<dependency>
       <groupId>com.thoughtworks.proxytoys</groupId>
       <artifactId>proxytoys</artifactId>
       <version>1.0</version>
       <type>jar</type>
       <optional>true</optional>
</dependency>

使用Morphia像JPA或Hibernate进行元注解annotate:

[...]
@Entity
public class Person {
       @Id private ObjectId id;
       [...

编制一个DAO来操作Person。

Datastore ds = ...; // like new Morphia(new Mongo()).createDatastore("hr")
morphia.map(Person.class);

ds.save(new Person("Mister", "GOD", null, 0));

更多操作见:https://github.com/mongodb/morphia

 

MongoDB的优化锁

 

猜你喜欢