spring版本4.1.6+morphia版本0.11
web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-morphia.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<!-- 当hibernate+spring配合使用的时候,如果设置了lazy=true,那么在读取数据的时候,当读取了父数据后, hibernate会自动关闭session,这样,当要使用子数据的时候,系统会抛出lazyinit的错误,
这时就需要使用spring提供的 OpenSessionInViewFilter,OpenSessionInViewFilter主要是保持Session状态
知道request将全部页面发送到客户端,这样就可以解决延迟加载带来的问题 -->
<filter>
<filter-name>openSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>openSessionInViewFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<async-supported>true</async-supported>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
</web-app>
log4j.properties 配置
#定义LOG输出级别
log4j.rootLogger=INFO,Console,File
#定义日志输出目的地为控制台
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
#可以灵活地指定日志输出格式,下面一行是指定具体的格式
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n
#文件大小到达指定尺寸的时候产生一个新的文件
log4j.appender.File = org.apache.log4j.RollingFileAppender
#指定输出目录
log4j.appender.File.File = logs/ssm.log
#定义文件最大大小
log4j.appender.File.MaxFileSize = 10MB
# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n
spring-mongo.properties
##mongo config
mongo.server.host=localhost
mongo.server.port=27017
mongo.server.connectionsperHost=20
mongo.server.threadsAllowedToBlockForConnectionMultiplier=10
mongo.server.dbName=user
mongo.server.user=root
mongo.server.pwd=root
spring-morphia.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:util="http://www.springframework.org/schema/util"
xmlns:cache="http://www.springframework.org/schema/cache" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache-4.0.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!-- :所有类进行扫描,以完成Bean创建和自动依赖注入的功能 -->
<context:component-scan base-package="cn.yc" />
<!-- :启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
<bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" />
<!-- 引入配置文件 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:spring-jdbc.properties" />
</bean>
<!-- <context:property-placeholder location="classpath:spring-mongo.properties"
/> -->
<!-- 使用工厂创建mongo实例 -->
<bean id="mongoClient" class="cn.yc.comm.config.MongoClientFactoryBean">
<!-- 设定服务器列表,默认为localhost:27017 -->
<property name="serverStrings">
<array>
<value>127.0.0.1:27017</value>
</array>
</property>
</bean>
<!-- 使用工厂创建morphia实例,同时完成类映射操作 -->
<bean id="morphia" class="cn.yc.comm.config.MorphiaFactoryBean">
<!-- 指定要扫描的POJO包路径 -->
<property name="mapPackages">
<array>
<value>cn.yc.comm.bean</value>
</array>
</property>
<!-- 指定要映射的类 -->
<!-- <property name="mapClasses"> <array> <value>me.watchzerg.test.morphia.pojo.Hotel</value>
<value>me.watchzerg.test.morphia.pojo.Address</value> </array> </property> -->
<!-- 扫描包时是否忽略不可用的类,默认为false -->
<!-- <property name="ignoreInvalidClasses" value="false"/> -->
</bean>
<!-- 使用工厂创建datastore,同时完成index和caps的确认操作 -->
<bean id="datastore" class="cn.yc.comm.config.DatastoreFactoryBean">
<property name="morphia" ref="morphia" />
<property name="mongoClient" ref="mongoClient" />
<!-- collection的名称 -->
<property name="dbName" value="${mongo.server.dbName}" />
<!-- 用户名和密码可以为空 -->
<property name="username" value="${mongo.server.user" />
<property name="password" value="${mongo.server.pwd" />
<!-- 是否进行index和caps的确认操作,默认为flase -->
<property name="toEnsureIndexes" value="true" />
<property name="toEnsureCaps" value="true" />
</bean>
<!-- 全局配置 -->
<bean id="config" class="cn.yicha.config.Config">
</bean>
<!-- ===============以下是具体DAO的实现===================== -->
<!-- 测试 -->
<bean id="hotelDao" class="cn.yc.comm.dao.HotelDao">
<constructor-arg ref="datastore" />
</bean>
</beans>
spring-mvc.xml 配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
<context:component-scan base-package="cn.yc.comm.action" />
<!--避免IE执行AJAX时,返回JSON出现下载文件 -->
<bean id="mappingJackson2HttpMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>text/json;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
<bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJackson2HttpMessageConverter" /> <!-- JSON转换器 -->
</list>
</property>
</bean>
<!-- String 字符转转码 json 数据配置 -->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- 对静态资源文件的访问 方案一 (二选一) -->
<mvc:default-servlet-handler />
<!-- 对静态资源文件的访问 方案二 (二选一) -->
<!-- <mvc:resources mapping="/images/**" location="/images/" cache-period="31556926"/>
<mvc:resources mapping="/js/**" location="/js/" cache-period="31556926"/>
<mvc:resources mapping="/css/**" location="/css/" cache-period="31556926"/> -->
<!-- 定义跳转的文件的前后缀 ,视图模式配置 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 默认编码 -->
<property name="defaultEncoding" value="utf-8" />
<!-- 文件大小最大值 -->
<property name="maxUploadSize" value="10485760000" />
<!-- 内存中的最大值 -->
<property name="maxInMemorySize" value="40960" />
</bean>
</beans>
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.yc</groupId>
<artifactId>mongo</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>spring-mongo</name>
<url>http://maven.apache.org</url>
<!-- 配置文件 -->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- junit版本 -->
<junit.version>4.11</junit.version>
<spring.version>4.1.6.RELEASE</spring.version>
<!-- mongo.driver版本 -->
<mongo.version>2.12.5</mongo.version>
<!-- mongodb框架版本 -->
<morphia.version>0.110</morphia.version>
<!-- dom4j版本 -->
<dom4j.version>1.6.1</dom4j.version>
<!-- jsp版本 -->
<jsp.version>2.0</jsp.version>
<!-- servlet版本 -->
<servlet.version>3.1.0</servlet.version>
<!-- slf4j版本 -->
<slf4j.version>1.7.5</slf4j.version>
<!-- log4j版本 -->
<log4j.version>1.2.17</log4j.version>
<!-- freemarker版本 -->
<freemarker.version>2.3.20</freemarker.version>
<!-- jackson版本 -->
<jackson.version>2.5.1</jackson.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- apache-commons start -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-exec</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.6</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.2</version>
</dependency>
<!-- apache-commons end -->
<!-- spring依赖开始 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc-portlet</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-instrument</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-instrument-tomcat</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring依赖结束 -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.6.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>${mongo.version}</version>
</dependency>
<dependency>
<groupId>org.mongodb.morphia</groupId>
<artifactId>morphia</artifactId>
<version>${morphia.version}</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>${dom4j.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>${jsp.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet.version}</version>
</dependency>
<!-- lsf4j,log4j依赖开始 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<!-- lsf4j,log4j依赖结束 -->
<!-- freemarker依赖开始 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>${freemarker.version}</version>
</dependency>
<!-- freemarker依赖结束 -->
<!-- jackson依赖开始 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- jackson依赖结束 -->
</dependencies>
<build>
<finalName>mongo</finalName>
</build>
</project>
MongoClient 工厂类
public class MongoClientFactoryBean extends AbstractFactoryBean<Mongo>{
// 表示服务器列表(主从复制或者分片)的字符串数组
private String[] serverStrings;
// mongoDB配置对象 使用默认配置
private MongoClientOptions mongoClientOptions=new MongoClientOptions.Builder().build();
@Override
public Class<?> getObjectType() {
return Mongo.class;
}
public String[] getServerStrings() {
return serverStrings;
}
public void setServerStrings(String[] serverStrings) {
this.serverStrings = serverStrings;
}
@Override
protected MongoClient createInstance() throws Exception {
MongoClient mongoClient =null;
if (null!=mongoClientOptions) {
mongoClient = new MongoClient(getServerList(), mongoClientOptions);
}else {
mongoClient = new MongoClient(getServerList());
}
return mongoClient;
}
/**
* 根据服务器字符串列表,解析出服务器对象列表
* @Title: getServerList
*
* @return
* @throws Exception
*/
private List<ServerAddress> getServerList() throws Exception {
List<ServerAddress> serverList = new ArrayList<ServerAddress>();
try {
for (String serverString : serverStrings) {
String[] temp = serverString.split(":");
String host = temp[0];
if (temp.length > 2) {
throw new IllegalArgumentException(
"Invalid server address string: " + serverString);
}
if (temp.length == 2) {
serverList.add(new ServerAddress(host, Integer
.parseInt(temp[1])));
} else {
serverList.add(new ServerAddress(host));
}
}
return serverList;
} catch (Exception e) {
throw new Exception(
"Error while converting serverString to ServerAddressList",
e);
}
}
}
MorphiaFactoryBean 返回 morphia实例
public class MorphiaFactoryBean extends AbstractFactoryBean<Morphia>{
/**
* 3 * 要扫描并映射的包 4
*/
private String[] mapPackages;
/**
* 要映射的类
*/
private String[] mapClasses;
/**
* 扫描包时,是否忽略不映射的类 这里按照Morphia的原始定义,默认设为false
*/
private boolean ignoreInvalidClasses;
@Override
protected Morphia createInstance() throws Exception {
Morphia m = new Morphia();
if (mapPackages != null) {
for (String packageName : mapPackages) {
m.mapPackage(packageName, ignoreInvalidClasses);
}
}
if (mapClasses != null) {
for (String entityClass : mapClasses) {
m.map(Class.forName(entityClass));
}
}
return m;
}
public String[] getMapPackages() {
return mapPackages;
}
public void setMapPackages(String[] mapPackages) {
this.mapPackages = mapPackages;
}
public String[] getMapClasses() {
return mapClasses;
}
public void setMapClasses(String[] mapClasses) {
this.mapClasses = mapClasses;
}
public boolean isIgnoreInvalidClasses() {
return ignoreInvalidClasses;
}
public void setIgnoreInvalidClasses(boolean ignoreInvalidClasses) {
this.ignoreInvalidClasses = ignoreInvalidClasses;
}
@Override
public Class<?> getObjectType() {
return Morphia.class;
}
}
DatastoreFactoryBean
public class DatastoreFactoryBean extends AbstractFactoryBean<Datastore> {
private Morphia morphia; // morphia实例,最好是单例
private MongoClient mongoClient; // mongoClient实例,最好是单例
private String dbName; // 数据库名
private String username; // 用户名,可为空
private String password; // 密码,可为空
private boolean toEnsureIndexes = false; // 是否确认索引存在,默认false
private boolean toEnsureCaps = false; // 是否确认caps存在,默认false
@Override
protected Datastore createInstance() throws Exception {
DB db = mongoClient.getDB(dbName);
/* if (db.isAuthenticated()) {
db.authenticate(username, password.toCharArray());
}*/
Datastore ds = morphia.createDatastore(mongoClient, dbName);
if(toEnsureIndexes){
ds.ensureIndexes();
}
if(toEnsureCaps){
ds.ensureCaps();
}
return ds;
}
public Morphia getMorphia() {
return morphia;
}
public void setMorphia(Morphia morphia) {
this.morphia = morphia;
}
public MongoClient getMongoClient() {
return mongoClient;
}
public void setMongoClient(MongoClient mongoClient) {
this.mongoClient = mongoClient;
}
public String getDbName() {
return dbName;
}
public void setDbName(String dbName) {
this.dbName = dbName;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isToEnsureIndexes() {
return toEnsureIndexes;
}
public void setToEnsureIndexes(boolean toEnsureIndexes) {
this.toEnsureIndexes = toEnsureIndexes;
}
public boolean isToEnsureCaps() {
return toEnsureCaps;
}
public void setToEnsureCaps(boolean toEnsureCaps) {
this.toEnsureCaps = toEnsureCaps;
}
@Override
public Class<?> getObjectType() {
return Datastore.class;
}
@Override
public void afterPropertiesSet() throws Exception {
super.afterPropertiesSet();
if (mongoClient == null) {
throw new IllegalStateException("mongoClient is not set");
}
if (morphia == null) {
throw new IllegalStateException("morphia is not set");
}
}
}
简单测试
po对象
@Entity(value="hotel",noClassnameStored=true)
@Indexes( @Index("name, stars") )
public class Hotel {
@Id
@JsonIgnore
private ObjectId id;
private String name;
private int stars;
@Embedded
private Address address;
public ObjectId getId() {
return id;
}
public void setId(ObjectId id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getStars() {
return stars;
}
public void setStars(int stars) {
this.stars = stars;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
@Embedded
public class Address {
private String street;
private String city;
private String postCode;
private String country;
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPostCode() {
return postCode;
}
public void setPostCode(String postCode) {
this.postCode = postCode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
dao层 在xml重配置注入Datastore
public class HotelDao extends BasicDAO<Hotel, ObjectId> {
protected HotelDao(Datastore ds) {
super(ds);
}
}
service层
@Service
public class HotelService {
@Autowired
private HotelDao hotelDao;
public int save(Hotel hotel) {
Key<Hotel> key = hotelDao.save(hotel);
if (null != key) {
return 1;
}
return 0;
}
public List<Hotel> getHotels() {
Query<Hotel> query = this.hotelDao.createQuery().filter("address.city", "北京");
List<Hotel> hotels = this.hotelDao.find(query).asList();
return hotels;
}
}
controller
@Controller
@RequestMapping("/hotel")
@Scope("prototype")
public class HotelAction {
@Autowired
private HotelService hotelService;
@RequestMapping(value = "/save", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> save(Hotel hotel) {
Map<String, Object> result = new HashMap<String, Object>();
int save = hotelService.save(hotel);
result.put("status", save);
return result;
}
@RequestMapping(value = "/getHotels", method = RequestMethod.GET)
@ResponseBody
public List<Hotel> getHotels() {
Map<String, Object> result = new HashMap<String, Object>();
List<Hotel> hotels = hotelService.getHotels();
result.put("data", hotels);
return hotels;
}
}