`
jzkangta
  • 浏览: 161031 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Spring和Morphia,MongoDB的简单封装以及自增ID的实现(转)

阅读更多

原文地址:http://www.oschina.net/code/snippet_98659_3681
一个对Spring和Morphia的简单封装,主要针对Mongo的自增ID实现以及方便与Spring的集成。
标签: Spring , mongodb , morphia , nosql
代码片段(15)
[代码] [Java]代码
01
package com.paojiao.nosql.mongo;
02

03
import com.google.code.morphia.annotations.Entity;
04
import com.google.code.morphia.annotations.Id;
05

06
import java.io.Serializable;
07

08
/**
09
* Created by IntelliJ IDEA.
10
* User: Arden
11
* Date: 11-3-26
12
* Time: 下午12:42
13
* To change this template use File | Settings | File Templates.
14
*/
15
@Entity(value = "sequence", noClassnameStored=true)
16
public class MongoSequence implements Serializable {
17
    @Id
18
    private String collName;
19

20
    private Long value;
21

22
    public MongoSequence(){
23
    }
24

25
    public MongoSequence(String collName) {
26
        this.collName = collName;
27
    }
28

29
    public String getCollName() {
30
        return collName;
31
    }
32

33
    public void setCollName(String collName) {
34
        this.collName = collName;
35
    }
36

37
    public Long getValue() {
38
        return value;
39
    }
40

41
    public void setValue(Long value) {
42
        this.value = value;
43
    }
44
}
[代码] [Java]代码
01
package com.paojiao.nosql.mongo;
02

03
import com.google.code.morphia.Datastore;
04
import com.google.code.morphia.Morphia;
05
import com.mongodb.Mongo;
06
import com.paojiao.session.Session;
07
import org.slf4j.Logger;
08
import org.slf4j.LoggerFactory;
09

10
import java.util.Map;
11

12
/**
13
* Created by IntelliJ IDEA.
14
* User: Arden
15
* Date: 11-3-26
16
* Time: 下午12:55
17
* To change this template use File | Settings | File Templates.
18
*/
19
public class MongoSequenceManager extends MongoDAO<MongoSequence, String> {
20
    // mongodb日志记录器
21
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
22
    // 序列映射
23
    private Map<String, Long> sequenceMap = null;
24

25
    public MongoSequenceManager(Datastore ds) {
26
        super(ds);
27
        this.entityClazz = MongoSequence.class;
28
    }
29

30
    public void setSequenceMap(Map<String, Long> sequenceMap) {
31
        this.sequenceMap = sequenceMap;
32
    }
33

34
    /**
35
     * 获得序列初始值
36
     * @param collName
37
     * @return
38
     */
39
    public Long getSequenceStartNumber(String collName) {
40
        Long startNumber = this.sequenceMap.get(collName);
41
        if (startNumber == null) {
42
            return 1L;
43
        }
44
        return startNumber;
45
    }
46
}
[代码] [Java]代码
001
package com.paojiao.nosql.mongo;
002

003
import com.google.code.morphia.Datastore;
004
import com.google.code.morphia.DatastoreImpl;
005
import com.google.code.morphia.Key;
006
import com.google.code.morphia.Morphia;
007
import com.google.code.morphia.dao.DAO;
008
import com.google.code.morphia.query.Query;
009
import com.google.code.morphia.query.QueryResults;
010
import com.google.code.morphia.query.UpdateOperations;
011
import com.google.code.morphia.query.UpdateResults;
012
import com.mongodb.DBCollection;
013
import com.mongodb.Mongo;
014
import com.mongodb.WriteConcern;
015
import com.mongodb.WriteResult;
016

017
import java.lang.reflect.ParameterizedType;
018
import java.util.ArrayList;
019
import java.util.List;
020

021
/**
022
* Created by IntelliJ IDEA.
023
* User: Arden
024
* Date: 11-3-15
025
* Time: 下午5:11
026
* To change this template use File | Settings | File Templates.
027
*/
028
@SuppressWarnings({ "unchecked", "rawtypes" })
029
public class MongoDAO<T, K> {
030

031
    protected Class<T> entityClazz;
032
    protected DatastoreImpl ds;
033

034
    protected MongoDAO(Datastore ds) {
035
        this.ds = (DatastoreImpl) ds;
036
    }
037

038
    public void setEntityClazz(Class<T> entityClazz) {
039
        this.entityClazz = entityClazz;
040
    }
041

042
    public void setDs(DatastoreImpl ds) {
043
        this.ds = ds;
044
    }
045

046
    /**
047
     * Converts from a List<Key> to their id values
048
     *
049
     * @param keys
050
     * @return
051
     */
052
    protected List<?> keysToIds(List<Key<T>> keys) {
053
        ArrayList ids = new ArrayList(keys.size() * 2);
054
        for (Key<T> key : keys)
055
            ids.add(key.getId());
056
        return ids;
057
    }
058

059
    /** The underlying collection for this DAO */
060
    public DBCollection getCollection() {
061
        return ds.getCollection(entityClazz);
062
    }
063

064

065
    /* (non-Javadoc)
066
     * @see com.google.code.morphia.DAO#createQuery()
067
     */
068
    public Query<T> createQuery() {
069
        return ds.createQuery(entityClazz);
070
    }
071

072
    /* (non-Javadoc)
073
     * @see com.google.code.morphia.DAO#createUpdateOperations()
074
     */
075
    public UpdateOperations<T> createUpdateOperations() {
076
        return ds.createUpdateOperations(entityClazz);
077
    }
078

079
    /* (non-Javadoc)
080
     * @see com.google.code.morphia.DAO#getEntityClass()
081
     */
082
    public Class<T> getEntityClass() {
083
        return entityClazz;
084
    }
085

086
    /* (non-Javadoc)
087
     * @see com.google.code.morphia.DAO#save(T)
088
     */
089
    public Key<T> save(T entity) {
090
        return ds.save(entity);
091
    }
092

093
    /* (non-Javadoc)
094
     * @see com.google.code.morphia.DAO#save(T, com.mongodb.WriteConcern)
095
     */
096
    public Key<T> save(T entity, WriteConcern wc) {
097
        return ds.save(entity, wc);
098
    }
099
    /* (non-Javadoc)
100
     * @see com.google.code.morphia.DAO#updateFirst(com.google.code.morphia.query.Query, com.google.code.morphia.query.UpdateOperations)
101
     */
102
    public UpdateResults<T> updateFirst(Query<T> q, UpdateOperations<T> ops) {
103
        return ds.updateFirst(q, ops);
104
    }
105

106
    /* (non-Javadoc)
107
     * @see com.google.code.morphia.DAO#update(com.google.code.morphia.query.Query, com.google.code.morphia.query.UpdateOperations)
108
     */
109
    public UpdateResults<T> update(Query<T> q, UpdateOperations<T> ops) {
110
        return ds.update(q, ops);
111
    }
112

113
    /* (non-Javadoc)
114
     * @see com.google.code.morphia.DAO#delete(T)
115
     */
116
    public WriteResult delete(T entity) {
117
        return ds.delete(entity);
118
    }
119

120
    /* (non-Javadoc)
121
     * @see com.google.code.morphia.DAO#delete(T, com.mongodb.WriteConcern)
122
     */
123
    public WriteResult delete(T entity, WriteConcern wc) {
124
        return ds.delete(entity, wc);
125
    }
126

127
    /* (non-Javadoc)
128
     * @see com.google.code.morphia.DAO#deleteById(K)
129
     */
130
    public WriteResult deleteById(K id) {
131
        return ds.delete(entityClazz, id);
132
    }
133

134
    /* (non-Javadoc)
135
     * @see com.google.code.morphia.DAO#deleteByQuery(com.google.code.morphia.query.Query)
136
     */
137
    public WriteResult deleteByQuery(Query q) {
138
        return ds.delete(q);
139
    }
140

141
    /* (non-Javadoc)
142
     * @see com.google.code.morphia.DAO#get(K)
143
     */
144
    public T get(K id) {
145
        return ds.get(entityClazz, id);
146
    }
147

148
    /* (non-Javadoc)
149
     * @see com.google.code.morphia.DAO#findIds(java.lang.String, java.lang.Object)
150
     */
151
    public List<T> findIds(String key, Object value) {
152
        return (List<T>) keysToIds(ds.find(entityClazz, key, value).asKeyList());
153
    }
154

155
    /* (non-Javadoc)
156
     * @see com.google.code.morphia.DAO#findIds()
157
     */
158
    public List<Key<T>> findIds() {
159
        return (List<Key<T>>) keysToIds(ds.find(entityClazz).asKeyList());
160
    }
161

162
    /* (non-Javadoc)
163
     * @see com.google.code.morphia.DAO#findIds(com.google.code.morphia.query.Query)
164
     */
165
    public List<Key<T>> findIds(Query<T> q) {
166
        return (List<Key<T>>) keysToIds(q.asKeyList());
167
    }
168

169
    /* (non-Javadoc)
170
     * @see com.google.code.morphia.DAO#exists(java.lang.String, java.lang.Object)
171
     */
172
    public boolean exists(String key, Object value) {
173
        return exists(ds.find(entityClazz, key, value));
174
    }
175

176
    /* (non-Javadoc)
177
     * @see com.google.code.morphia.DAO#exists(com.google.code.morphia.query.Query)
178
     */
179
    public boolean exists(Query<T> q) {
180
        return ds.getCount(q) > 0;
181
    }
182

183
    /* (non-Javadoc)
184
     * @see com.google.code.morphia.DAO#count()
185
     */
186
    public long count() {
187
        return ds.getCount(entityClazz);
188
    }
189

190
    /* (non-Javadoc)
191
     * @see com.google.code.morphia.DAO#count(java.lang.String, java.lang.Object)
192
     */
193
    public long count(String key, Object value) {
194
        return count(ds.find(entityClazz, key, value));
195
    }
196

197
    /* (non-Javadoc)
198
     * @see com.google.code.morphia.DAO#count(com.google.code.morphia.query.Query)
199
     */
200
    public long count(Query<T> q) {
201
        return ds.getCount(q);
202
    }
203

204
    /* (non-Javadoc)
205
     * @see com.google.code.morphia.DAO#findOne(java.lang.String, java.lang.Object)
206
     */
207
    public T findOne(String key, Object value) {
208
        return ds.find(entityClazz, key, value).get();
209
    }
210

211
    /* (non-Javadoc)
212
     * @see com.google.code.morphia.DAO#findOne(com.google.code.morphia.query.Query)
213
     */
214
    public T findOne(Query<T> q) {
215
        return q.get();
216
    }
217

218
    /* (non-Javadoc)
219
     * @see com.google.code.morphia.DAO#find()
220
     */
221
    public QueryResults<T> find() {
222
        return createQuery();
223
    }
224

225
    /* (non-Javadoc)
226
     * @see com.google.code.morphia.DAO#find(com.google.code.morphia.query.Query)
227
     */
228
    public QueryResults<T> find(Query<T> q) {
229
        return q;
230
    }
231

232
    /* (non-Javadoc)
233
     * @see com.google.code.morphia.DAO#getDatastore()
234
     */
235
    public Datastore getDatastore() {
236
        return ds;
237
    }
238

239
    public void ensureIndexes() {
240
        ds.ensureIndexes(entityClazz);
241
    }
242

243
}
[代码] [Java]代码
01
package com.paojiao.nosql.mongo;
02

03
import com.google.code.morphia.DatastoreImpl;
04
import com.google.code.morphia.Morphia;
05
import com.mongodb.Mongo;
06

07
import java.util.List;
08

09
/**
10
* Created by IntelliJ IDEA.
11
* User: Arden
12
* Date: 11-3-26
13
* Time: 下午3:09
14
* To change this template use File | Settings | File Templates.
15
*/
16
public class MongoDataStore extends DatastoreImpl {
17
    private List<Class> entityClasses;
18

19
    public MongoDataStore(Morphia morphia, Mongo mongo) {
20
        super(morphia, mongo);
21
    }
22

23
    public MongoDataStore(Morphia morphia, Mongo mongo, String dbName, String username, char[] password) {
24
        super(morphia, mongo, dbName, username, password);
25
    }
26

27
    public MongoDataStore(Morphia morphia, Mongo mongo, String dbName) {
28
        super(morphia, mongo, dbName);
29
    }
30

31
    public void setEntityClasses(List<Class> entityClasses) {
32
        this.entityClasses = entityClasses;
33
    }
34

35
    /**
36
     * 初始化相关映射类
37
     */
38
    public void init() {
39
        System.out.println(this.entityClasses);
40
        if (this.entityClasses != null && !this.entityClasses.isEmpty()) {
41
            for (Class entityClass : entityClasses) {
42
                this.getMapper().addMappedClass(entityClass);
43
            }
44
        }
45
    }
46
}
[代码] [Java]代码
01
package com.paojiao.nosql.mongo;
02

03
import com.google.code.morphia.annotations.Id;
04
import com.google.code.morphia.annotations.PrePersist;
05
import com.google.code.morphia.query.Query;
06
import com.jrails.modules.spring.ServiceLocator;
07

08
import java.io.Serializable;
09

10
/**
11
* Created by IntelliJ IDEA.
12
* User: Arden
13
* Date: 11-3-26
14
* Time: 下午12:58
15
* To change this template use File | Settings | File Templates.
16
*/
17
public abstract class LongPKMongoEntity implements Serializable {
18
    @Id
19
    protected Long id;
20

21
    public Long getId() {
22
        return id;
23
    }
24

25
    public void setId(Long id) {
26
        this.id = id;
27
    }
28

29
    @PrePersist
30
    protected void prePersist() {
31
        if (id == null) {
32
            MongoSequenceManager mongoSequenceManager = (MongoSequenceManager) ServiceLocator.getService("mongoSequenceManager");
33
            String collName = this.getClass().getCanonicalName();
34
            MongoSequence sequence = mongoSequenceManager.get(collName);
35
            if (sequence == null) {
36
                sequence = new MongoSequence(collName);
37
                Long startNumber = mongoSequenceManager.getSequenceStartNumber(collName);
38
                sequence.setValue(startNumber);
39
            } else {
40
                sequence.setValue(sequence.getValue()+1);
41
            }
42
            mongoSequenceManager.save(sequence);
43
            this.id = sequence.getValue();
44
        }
45
    }
46
}
[代码] [Java]代码
01
package com.paojiao.nosql.mongo;
02

03
import com.google.code.morphia.annotations.Id;
04
import com.google.code.morphia.annotations.PrePersist;
05
import com.jrails.modules.spring.ServiceLocator;
06
import org.bson.types.ObjectId;
07

08
/**
09
* Created by IntelliJ IDEA.
10
* User: Arden
11
* Date: 11-3-26
12
* Time: 下午12:58
13
* To change this template use File | Settings | File Templates.
14
*/
15
public abstract class StringPKMongoEntity {
16
    @Id
17
    protected String id = new ObjectId().toString();
18

19
    public String getId() {
20
        return id;
21
    }
22

23
    public void setId(String id) {
24
        this.id = id;
25
    }
26
}
[代码] [Java]代码
01
package com.paojiao.nosql.mongo;
02

03
import com.google.code.morphia.annotations.Id;
04
import com.google.code.morphia.annotations.PrePersist;
05
import com.jrails.modules.spring.ServiceLocator;
06

07
import java.util.UUID;
08

09
/**
10
* Created by IntelliJ IDEA.
11
* User: Arden
12
* Date: 11-3-26
13
* Time: 下午12:58
14
* To change this template use File | Settings | File Templates.
15
*/
16
public abstract class UuidPKMongoEntity {
17
    @Id
18
    protected String id;
19

20
    public String getId() {
21
        return id;
22
    }
23

24
    public void setId(String id) {
25
        this.id = id;
26
    }
27

28
    @PrePersist
29
    protected void prePersist() {
30
        if (id == null) {
31
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
32
            this.id = uuid;
33
        }
34
    }
35
}
[代码] [Java]代码
01
<?xml version="1.0" encoding="utf-8"?>
02
<beans xmlns="http://www.springframework.org/schema/beans"
03
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
04
    xmlns:p="http://www.springframework.org/schema/p"
05
    xmlns:context="http://www.springframework.org/schema/context"
06
    xmlns:aop="http://www.springframework.org/schema/aop"
07
    xmlns:task="http://www.springframework.org/schema/task"
08
    xsi:schemaLocation="http://www.springframework.org/schema/beans
09
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
10
    http://www.springframework.org/schema/context
11
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
12
    http://www.springframework.org/schema/task
13
    http://www.springframework.org/schema/task/spring-task-3.0.xsd
14
    http://www.springframework.org/schema/aop
15
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
16

17
    <description>数据源</description>
18

19

20
    <!-- mongodb配置 -->
21
    <bean id="mongo" class="com.mongodb.Mongo">
22
        <constructor-arg value="192.168.1.130"/>
23
        <constructor-arg value="27017"/>
24
    </bean>
25

26
    <bean id="morphia" class="com.google.code.morphia.Morphia"/>
27

28
    <bean id="paojiaoMongoDatastore" class="com.paojiao.nosql.mongo.MongoDataStore" init-method="init">
29
        <constructor-arg ref="morphia"/>
30
        <!-- Mongo连接器 -->
31
        <constructor-arg ref="mongo"/>
32
        <!-- 数据库名 -->
33
        <constructor-arg value="paojiao"/>
34
        <!-- 用户名 -->
35
        <constructor-arg value="paojiao"/>
36
        <!-- 密码 -->
37
        <constructor-arg value="123456"/>
38

39
        <property name="entityClasses">
40
            <list>
41
                <value>com.paojiao.session.Session</value>
42
                <value>com.paojiao.session.User</value>
43
                <value>com.paojiao.nosql.mongo.MongoSequence</value>
44
            </list>
45
        </property>
46
    </bean>
47
</beans>
[代码] [Java]代码
01
<?xml version="1.0" encoding="utf-8"?>
02
<beans xmlns="http://www.springframework.org/schema/beans"
03
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
04
    xmlns:p="http://www.springframework.org/schema/p"
05
    xmlns:context="http://www.springframework.org/schema/context"
06
    xmlns:aop="http://www.springframework.org/schema/aop"
07
    xmlns:task="http://www.springframework.org/schema/task"
08
    xsi:schemaLocation="http://www.springframework.org/schema/beans
09
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
10
    http://www.springframework.org/schema/context
11
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
12
    http://www.springframework.org/schema/task
13
    http://www.springframework.org/schema/task/spring-task-3.0.xsd
14
    http://www.springframework.org/schema/aop
15
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
16
    <bean id="serviceLocator" class="com.jrails.modules.spring.ServiceLocator"/>
17

18
    <import resource="classpath:spring-datasource.xml"/>
19

20
    <bean id="sessionManager" class="com.paojiao.session.SessionManager">
21
        <constructor-arg ref="paojiaoMongoDatastore"/>
22
    </bean>
23

24
    <bean id="mongoSequenceManager" class="com.paojiao.nosql.mongo.MongoSequenceManager">
25
        <!-- Mongo数据源 -->
26
        <constructor-arg ref="paojiaoMongoDatastore"/>
27
        <property name="sequenceMap">
28
            <map>
29
                <entry key="com.paojiao.session.User" value="1000"/>
30
            </map>
31
        </property>
32
    </bean>
33

34
    <bean id="userManager" class="com.paojiao.session.UserManager">
35
        <!-- Mongo数据源 -->
36
        <constructor-arg ref="paojiaoMongoDatastore"/>
37
    </bean>
38
</beans>
[代码] [Java]代码
01
package com.paojiao.session;
02

03
import com.google.code.morphia.Datastore;
04
import com.google.code.morphia.Key;
05
import com.google.code.morphia.Morphia;
06
import com.mongodb.Mongo;
07
import com.paojiao.nosql.mongo.MongoDAO;
08
import org.bson.types.ObjectId;
09
import org.slf4j.Logger;
10
import org.slf4j.LoggerFactory;
11

12
import java.util.Calendar;
13

14
/**
15
* Created by IntelliJ IDEA.
16
* User: Arden
17
* Date: 11-3-26
18
* Time: 上午10:55
19
* To change this template use File | Settings | File Templates.
20
*/
21
public class SessionManager extends MongoDAO<Session, String> {
22
    // mongodb日志记录器
23
    private final Logger sessionLogger = LoggerFactory.getLogger("mongodataLogger");
24

25
    public SessionManager(Datastore ds) {
26
        super(ds);
27
        this.entityClazz = Session.class;
28
    }
29

30
    /**
31
     * 创建一个空session
32
     *
33
     * @param userid
34
     * @param username
35
     * @param module
36
     * @param device
37
     * @param rid
38
     * @return
39
     */
40
    public Session createSession(Long userid, String username, int module, int device, String rid) {
41
        Session session = new Session();
42
        session.setUserid(userid);
43
        session.setUsername(username);
44
        session.setModule(module);
45
        session.setDevice(device);
46
        session.setRid(rid);
47
        return session;
48
    }
49

50
    /**
51
     * 保存session
52
     * @param session
53
     * @return
54
     */
55
    public String saveSession(Session session) {
56
        Key key = this.save(session);
57
        return (String)key.getId();
58
    }
59
}
[代码] [Java]代码
001
package com.paojiao.session;
002

003
import com.google.code.morphia.annotations.Entity;
004
import com.google.code.morphia.annotations.Id;
005
import com.google.code.morphia.annotations.Indexed;
006
import com.google.code.morphia.annotations.Property;
007
import com.paojiao.nosql.mongo.StringPKMongoEntity;
008
import com.paojiao.nosql.mongo.UuidPKMongoEntity;
009
import org.bson.types.ObjectId;
010

011
import java.io.Serializable;
012
import java.util.Calendar;
013
import java.util.Date;
014
import java.util.HashMap;
015
import java.util.Map;
016

017
/**
018
* Created by IntelliJ IDEA.
019
* User: Arden
020
* Date: 11-3-26
021
* Time: 上午10:28
022
* To change this template use File | Settings | File Templates.
023
*/
024
@Entity(value = "sessions", noClassnameStored=true)
025
public class Session extends StringPKMongoEntity {
026
    // 用户ID
027
    @Indexed(name="i_userid", unique=true)  @Property("userid") protected Long userid = 0L;
028

029
    // 用户名
030
    @Indexed protected String username;
031

032
    // session创建时间
033
    @Property("creation_time") protected Date creationTime = Calendar.getInstance().getTime();
034

035
    // session访问时间
036
    @Property("accessed_time") protected Date accessedTime = creationTime;
037

038
    // 业务模块
039
    protected int module;
040

041
    // 用户的RID
042
    @Indexed(name="i_rid", unique=true) protected String rid;
043

044
    // 用户使用的终端(如:手机客户端(Iphone,Nokia等)
045
    protected int device = 1;
046

047
    // session超时时间
048
    protected int timeout = 30;
049

050
    // session详细内容
051
    protected Map<String,Object> data;
052

053
    public Long getUserid() {
054
        return userid;
055
    }
056

057
    public void setUserid(Long userid) {
058
        this.userid = userid;
059
    }
060

061
    public String getUsername() {
062
        return username;
063
    }
064

065
    public void setUsername(String username) {
066
        this.username = username;
067
    }
068

069
    public Date getCreationTime() {
070
        return creationTime;
071
    }
072

073
    public void setCreationTime(Date creationTime) {
074
        this.creationTime = creationTime;
075
    }
076

077
    public Date getAccessedTime() {
078
        return accessedTime;
079
    }
080

081
    public void setAccessedTime(Date accessedTime) {
082
        this.accessedTime = accessedTime;
083
    }
084

085
    public int getModule() {
086
        return module;
087
    }
088

089
    public void setModule(int module) {
090
        this.module = module;
091
    }
092

093
    public String getRid() {
094
        return rid;
095
    }
096

097
    public void setRid(String rid) {
098
        this.rid = rid;
099
    }
100

101
    public int getDevice() {
102
        return device;
103
    }
104

105
    public void setDevice(int device) {
106
        this.device = device;
107
    }
108

109
    public Map<String, Object> getData() {
110
        return data;
111
    }
112

113
    public void setData(Map<String, Object> data) {
114
        this.data = data;
115
    }
116

117
    public void setAttribute(String key, Object value) {
118
        if (this.data == null) {
119
            this.data = new HashMap<String,Object>();
120
        }
121
        this.data.put(key, value);
122
    }
123

124
    public Object getAttribute(String key) {
125
        if (this.data != null) {
126
            return this.data.get(key);
127
        }
128
        return null;
129
    }
130

131
    public int getTimeout() {
132
        return timeout;
133
    }
134

135
    public void setTimeout(int timeout) {
136
        this.timeout = timeout;
137
    }
138
}
[代码] [Java]代码
01
package com.paojiao.session;
02

03
import com.google.code.morphia.annotations.Entity;
04
import com.paojiao.nosql.mongo.LongPKMongoEntity;
05

06
/**
07
* Created by IntelliJ IDEA.
08
* User: Arden
09
* Date: 11-3-26
10
* Time: 下午5:22
11
* To change this template use File | Settings | File Templates.
12
*/
13
@Entity(value = "sessionusers", noClassnameStored=true)
14
public class User extends LongPKMongoEntity {
15
    private String name;
16

17
    public String getName() {
18
        return name;
19
    }
20

21
    public void setName(String name) {
22
        this.name = name;
23
    }
24
}
[代码] [Java]代码
01
/* --------------------------------------
02
* CREATED ON 2007-11-23 15:35:25
03
*
04
* MSN ardenemily@msn.com
05
* QQ 83058327(太阳里的雪)
06
* MOBILE 13590309275
07
* BLOG http://www.caojianghua.com
08
*
09
* ALL RIGHTS RESERVED BY ZHENUU CO,.LTD.
10
* --------------------------------------
11
*/
12
package com.jrails.modules.spring;
13

14
import org.apache.commons.logging.Log;
15
import org.apache.commons.logging.LogFactory;
16
import org.springframework.beans.BeansException;
17
import org.springframework.beans.factory.BeanFactory;
18
import org.springframework.beans.factory.BeanFactoryAware;
19

20
/**
21
* Spring业务查找器
22
*
23
* @author <a href="mailto:arden.emily@gmail.com">arden</a>
24
*/
25
public class ServiceLocator implements BeanFactoryAware {
26

27
    protected static final Log logger = LogFactory.getLog(ServiceLocator.class);
28
    private static BeanFactory beanFactory = null;
29
                                                              
30
    public void setBeanFactory(BeanFactory factory) throws BeansException {
31
        beanFactory = factory;
32
    }
33

34
    public static Object getBean(String beanName) {
35
        if (beanFactory != null) {
36
            return beanFactory.getBean(beanName);
37
        }
38
        return null;
39
    }
40

41
    public static Object getDao(String daoName) {
42
        return getBean(daoName);
43
    }
44

45
    public static Object getService(String serviceName) {
46
        return getBean(serviceName);
47
    }
48
}
[代码] [Java]代码
01
package com.paojiao.session;
02

03
import com.google.code.morphia.Datastore;
04
import com.paojiao.nosql.mongo.MongoDAO;
05

06
/**
07
* Created by IntelliJ IDEA.
08
* User: Administrator
09
* Date: 11-3-26
10
* Time: 下午5:23
11
* To change this template use File | Settings | File Templates.
12
*/
13
public class UserManager  extends MongoDAO<User, String> {
14
    public UserManager(Datastore ds) {
15
        super(ds);
16
    }
17
}
[代码] [Java]代码
view sourceprint?
01
package com.paojiao.session;
02

03
import com.jrails.modules.spring.ServiceLocator;
04
import com.paojiao.spring.SpringConfig;
05

06
/**
07
* Created by IntelliJ IDEA.
08
* User: Arden
09
* Date: 11-3-26
10
* Time: 上午11:00
11
* To change this template use File | Settings | File Templates.
12
*/
13
public class SessionTest {
14
    public static void main(String...args) {
15
        try {
16
            SpringConfig.init("spring.xml");
17
            SessionManager sessionManager = (SessionManager) ServiceLocator.getService("sessionManager");
18
            Session session = sessionManager.createSession(204L, "arden", 1, 1, "1234567890");
19
            //session.setId("aaaaaaaaaaaa");
20
            session.setAttribute("name", "ardenemily");
21
            session.setAttribute("email", "ardenemilyaa@paojiao.cn");
22
            String id = sessionManager.saveSession(session);
23
            System.out.println(id);
24
            Session s = sessionManager.get(id);
25
            if (s != null) {
26
                System.out.println(s.data.get("name"));
27
                System.out.println(s.data.get("email"));
28
            }
29
            boolean exists = sessionManager.exists("_id", id);
30
            System.out.println(exists);
31

32

33
            UserManager userManager = (UserManager) ServiceLocator.getService("userManager");
34
            User user = new User();
35
            user.setName("arden");
36
            userManager.save(user);
37

38
        } catch (Exception e) {
39
            e.printStackTrace();
40
        }
41
    }
42
}
分享到:
评论
1 楼 renwolang521 2011-09-26  
代码重新整理下吧,这个真没法看。

相关推荐

    使用Morphia框架操作mongodb

    MongoDB是一种流行的开源、分布式文档数据库,常用于处理大规模数据。在Java开发中,Morphia是一个优秀的对象数据映射(ODM...通过学习和实践,你将能够充分利用Morphia框架的强大功能,实现高效、灵活的MongoDB操作。

    spring MVC morphia mongo 整合的例子

    Spring MVC、Morphia 和 MongoDB 是三个在Java开发中常用于构建Web应用程序的关键技术。Spring MVC 是Spring框架的一部分,提供了一种模型-视图-控制器(MVC)架构模式,帮助开发者组织和处理Web应用的业务逻辑。...

    spring-mongodb-morphia:springdata-mongo morphia mongodb 学习

    在`spring-mongodb-morphia-master`这个项目中,你可以找到实际的代码示例,了解如何配置Spring Boot以支持MongoDB和Morphia,以及如何定义和使用Repository。项目中可能包含了以下关键组件: 1. `application....

    使用 Morphia 和 MongoDB 实现域模型持久性(ZZ)

    本篇文章将详细介绍如何使用 Morphia 和 MongoDB 来实现域模型的持久化。 首先,我们需要理解 Morphia 的基本概念。Morphia 将 Java 对象映射到 MongoDB 的文档结构,这包括实体类、数据存储、数据映射和查询API。...

    Morphia和MongoDB学习总结<三>

    **标题:“Morphia和MongoDB学习总结&lt;三&gt;”** 在本文中,我们将深入探讨Morphia,一个用于Java的MongoDB对象数据映射(ODM)库,以及它如何与MongoDB数据库进行交互。Morphia简化了在MongoDB中存储和检索Java对象的...

    morphia基于mongodb的基本开发

    morphia基于mongodb的基本开发

    Morphia 操作 MongoDB.pdf

    以下是一个简单的示例,展示了如何使用 Morphia 连接 MongoDB 并进行数据操作: ```java import org.mongodb.Mongo; import org.mongodb.MongoClient; import org.mongodb.gridfs.GridFS; import org.mongodb....

    Morphia 操作 MongoDB.docx

    此外,Morphia还支持更新、删除等操作,以及复杂的查询表达式和聚合操作。 【Morphia的优势】 1. 简化的API:Morphia提供了易于使用的Java对象映射,使得处理MongoDB数据变得简单。 2. 自动类型转换:Morphia能自动...

    使用Morphia和MongoDB实现域模型持久性

    本文解释了在文档和对象之间进行映射的好处,并演示了如何使用Morphia来实现这个功能。然后演示了如何持久保存、加载、删除和查询映射到 MongoDB的Java域模型。MongoDB是面向文档的数据库,用于存储并检索类似...

    mongodbWeb

    在本项目“mongodbWeb”中,结合Spring MVC框架和Morphia库,实现了对MongoDB数据库的操作封装,便于在Web应用中进行数据管理。 **Spring MVC与MongoDB结合** Spring MVC是Spring框架的一部分,它提供了模型-视图-...

    Spring整合MongoDB基于Maven

    本篇将详细介绍如何使用Maven来管理依赖,以及如何配置和使用Spring Data MongoDB来实现数据访问。 首先,我们需要在项目中引入Spring Data MongoDB和MongoDB Java驱动程序的Maven依赖。在`pom.xml`文件中添加以下...

    Morphia操作MongoDB

    【Morphia 操作 MongoDB 知识点详解】 Morphia 是一个针对 MongoDB 的 Java ORM(对象关系映射)框架,它允许开发者使用 Java 对象直接操作 MongoDB 数据库,简化了数据库操作。以下是对 Morphia 操作 MongoDB 的...

    mongoDB相关教程以及windows版mongodb

    它可能还会涉及异步操作、事务处理以及数据映射技术,例如使用Morphia或Spring Data MongoDB。 最后,"windows版本的mongodb"是MongoDB服务器的Windows平台安装包。安装MongoDB在Windows上通常包括下载msi安装文件...

    spring集成mongodb

    以上代码展示了如何在 Spring 4.2 中集成 MongoDB 和 Morphia 1.1。通过这种方式,你可以利用 Spring 的强大功能和 MongoDB 的灵活性来构建高性能的 Java 应用。 在实际开发中,你可能还需要考虑异常处理、事务管理...

    Mongo的ORM框架的学习Morphia

    在本文中,我们将探讨MongoDB的ORM框架Morphia,并结合Spring Data MongoDB的使用来创建一个集成应用。ORM(对象关系映射)框架是将数据库操作转化为对象模型的方法,简化了开发过程,使得开发者可以专注于业务逻辑...

    mongodb+springmvc+morphia

    后续提交放在https://github.com/zdsiyan/watermelon 上, 用eclipse导入该工程需安装m2eclipse,jetty等查件....&lt;project-modules id="moduleCoreId" project-version="1.5.0"&gt; &lt;/project-modules&gt;

    morphia-mongodb-examples:用于MongoDB的Morphia ODM的示例

    MongoDB是一种流行的NoSQL数据库系统,它以JSON格式存储数据,具有高度的可扩展性和灵活性。Morphia是为MongoDB设计的一个强大的Object Document Mapper (ODM)库,它允许Java开发者以面向对象的方式与MongoDB进行...

    Mongo集成Spring

    6. **Morphia**: `Mongo_Morthia_Spring` 可能指的是使用 Morphia 框架集成 MongoDB 和 Spring。Morphia 是一个针对 MongoDB 的对象数据映射库,它简化了将 Java 对象与 MongoDB 文档之间的转换。虽然 Spring Data ...

    morphia.jar和mongo.jar

    标题中的“morphia.jar”和“mongo.jar”指的是两个与MongoDB数据库操作相关的Java库文件。MongoDB是一个流行的开源、分布式文档型数据库,而Morphia则是Java开发人员用来操作MongoDB的一个对象数据映射(ODM)框架...

Global site tag (gtag.js) - Google Analytics