java-spring与mongodb的整合方式一 自动注入xml(1)
- UID
- 1066743
|
java-spring与mongodb的整合方式一 自动注入xml(1)
新建需要操作的class类
package com.mongo.entity;
public class User {
private String name;
private String message;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
操作mongodb的接口和实现类: (基类和继承类)
基类:GenericReposityImpl
package com.mongo.reposity.Impl;
import java.util.List;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import com.mongo.reposity.GenericReposity;
import com.mongodb.Mongo;
import com.mongodb.WriteResult;
public class GenericReposityImpl<T> extends MongoTemplate implements GenericReposity<T> {
public GenericReposityImpl(Mongo mongo, String databaseName) {
super(mongo, databaseName);
}
public List<T> getAllObjects(Class<T> clazz) {
return findAll(clazz);
}
public void saveObject(Object obj) {
insert(obj);
}
public void saveObjects(List<T> objects) {
for (T t : objects) {
insert(t);
}
}
public T getObject(Class<T> clazz, String id) {
return findOne(new Query(Criteria.where("id").is(id)), clazz);
}
public WriteResult updateObject(Class<T> clazz, String id, String name) {
return updateFirst(new Query(Criteria.where("id").is(id)),
Update.update("name", name), clazz);
}
public void deleteObject(Class<T> clazz, String id) {
remove(new Query(Criteria.where("id").is(id)), clazz);
}
public void createDbCollection(Class<T> clazz) {
if (collectionExists(clazz)) {
createCollection(clazz);
}
}
public void dropDbCollection(Class<T> clazz) {
if (collectionExists(clazz)) {
dropCollection(clazz);
}
}
} |
|
|
|
|
|