`
jzkangta
  • 浏览: 156683 次
  • 性别: 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  
代码重新整理下吧,这个真没法看。

相关推荐

Global site tag (gtag.js) - Google Analytics