mongo的開始
最近公司的一些業(yè)務(wù)擴(kuò)展讓我們需要在傳統(tǒng)的庫中不斷的進(jìn)行修改,考慮到日后的發(fā)展,決定引入mongodb來支持部分業(yè)務(wù)模型
MongoDB是一個(gè)介于關(guān)系數(shù)據(jù)庫和非關(guān)系數(shù)據(jù)庫之間的產(chǎn)品佛致,是非關(guān)系數(shù)據(jù)庫當(dāng)中功能最豐富触机,最像關(guān)系數(shù)據(jù)庫的雾袱。他支持的數(shù)據(jù)結(jié)構(gòu)非常松散,是類似json的bson格式,因此可以存儲比較復(fù)雜的數(shù)據(jù)類型。Mongo最大的特點(diǎn)是他支持的查詢語言非常強(qiáng)大谋作,其語法有點(diǎn)類似于面向?qū)ο蟮牟樵冋Z言,幾乎可以實(shí)現(xiàn)類似關(guān)系數(shù)據(jù)庫單表查詢的絕大部分功能列吼,而且還支持對數(shù)據(jù)建立索引幽崩。
和spring的集成
spring-data-mongo和spring的集成是比較簡單,比較spring-data-mongo已經(jīng)替你做了很多的事情了
- 首先在我們的spring的xml文件中增加注解支持,并掃描你要增加的配置文件的位置
<context:annotation-config/>
<context:component-scan base-package="com.*.*"/>
- 配置數(shù)據(jù)層模板(mongoTemplate)
@Configuration
public class MongoConfig {
private static final ResourceBundle bundle = ResourceBundle.getBundle("mongodb");
private String uri = bundle.getString("mongo.uri");
public
@Bean
MongoDbFactory mongoDbFactory() throws Exception {
// mongo連接池的參數(shù)
MongoClientOptions.Builder mongoClientOptions =
MongoClientOptions.builder().socketTimeout(3000).connectTimeout(3000)
.connectionsPerHost(20);
// 設(shè)置連接池
MongoClientURI mongoClientURI = new MongoClientURI(uri, mongoClientOptions);
return new SimpleMongoDbFactory(mongoClientURI);
}
public
@Bean
MongoTemplate mongoTemplate() throws Exception {
return new MongoTemplate(mongoDbFactory());
}
}
這里需要注意的東西是mongo.uri
寞钥,這貨是個(gè)啥玩意呢慌申?
讓我們?nèi)ノ覀兊膍ongo.properties文件中查看下具體的配置
mongo.uri=mongodb://userName:passWord@127.0.0.1:27017/DBname
沒錯(cuò),這就是核心配置,就像mysql的驅(qū)動連接方式一樣,spring-data-mongo也可以采用url的方式連接
上述文件中的userName
、passWord
理郑、DBname
替換成你自己的參數(shù)就OK了
- 基礎(chǔ)base操作(基類的聚合)
下面我參照了 lynnlovemin 同學(xué)這篇文章的基類(進(jìn)行了部分修改),進(jìn)行了集成操作
<b>我的base類</b>
/**
* <p>
* mongo查詢基類
* </p>
*
* @author wangguangdong
* @version 1.0
* @Date 16/3/8
*/
@Component
public abstract class BaseMongoDAOImpl<T> {
/**
* spring mongodb 集成操作類
*/
protected MongoTemplate mongoTemplate;
public List<T> find(Query query) {
return mongoTemplate.find(query, this.getEntityClass());
}
public T findOne(Query query) {
return mongoTemplate.findOne(query, this.getEntityClass());
}
public void update(Query query, Update update) {
mongoTemplate.findAndModify(query, update, this.getEntityClass());
}
public T save(T entity) {
mongoTemplate.insert(entity);
return entity;
}
public T findById(String id) {
return mongoTemplate.findById(id, this.getEntityClass());
}
//@Override
public T findById(String id, String collectionName) {
return mongoTemplate.findById(id, this.getEntityClass(), collectionName);
}
public long count(Query query) {
return mongoTemplate.count(query, this.getEntityClass());
}
/**
* 獲取需要操作的實(shí)體類class
*
* @return
*/
private Class<T> getEntityClass() {
return ReflectionUtils.getSuperClassGenricType(getClass());
}
public void remove(Query query) {
mongoTemplate.remove(query, this.getEntityClass());
}
/**
* 注入mongodbTemplate
*
* @param mongoTemplate
*/
protected abstract void setMongoTemplate(MongoTemplate mongoTemplate);
}
<b>ReflectionUtils反射工具類</b>
/**
* <p>
* 反射工具類
* </p>
*
* @author wangguangdong
* @version 1.0
* @Date 16/3/8
*/
public class ReflectionUtils {
private static Logger logger = Logger.getLogger(ReflectionUtils.class);
/**
* 調(diào)用Getter方法.
*/
public static Object invokeGetterMethod(Object obj, String propertyName) {
String getterMethodName = "get" + StringUtils.capitalize(propertyName);
return invokeMethod(obj, getterMethodName, new Class[] {}, new Object[] {});
}
/**
* 調(diào)用Setter方法.使用value的Class來查找Setter方法.
*/
public static void invokeSetterMethod(Object obj, String propertyName, Object value) {
invokeSetterMethod(obj, propertyName, value, null);
}
/**
* 調(diào)用Setter方法.
*
* @param propertyType 用于查找Setter方法,為空時(shí)使用value的Class替代.
*/
public static void invokeSetterMethod(Object obj, String propertyName, Object value,
Class<?> propertyType) {
Class<?> type = propertyType != null ? propertyType : value.getClass();
String setterMethodName = "set" + StringUtils.capitalize(propertyName);
invokeMethod(obj, setterMethodName, new Class[] {type}, new Object[] {value});
}
/**
* 直接讀取對象屬性值, 無視private/protected修飾符, 不經(jīng)過getter函數(shù).
*/
public static Object getFieldValue(final Object obj, final String fieldName) {
Field field = getAccessibleField(obj, fieldName);
if (field == null) {
throw new IllegalArgumentException(
"Could not find field [" + fieldName + "] on target [" + obj + "]");
}
Object result = null;
try {
result = field.get(obj);
} catch (IllegalAccessException e) {
logger.error("不可能拋出的異常" + e.getMessage());
}
return result;
}
/**
* 直接設(shè)置對象屬性值, 無視private/protected修飾符, 不經(jīng)過setter函數(shù).
*/
public static void setFieldValue(final Object obj, final String fieldName, final Object value) {
Field field = getAccessibleField(obj, fieldName);
if (field == null) {
throw new IllegalArgumentException(
"Could not find field [" + fieldName + "] on target [" + obj + "]");
}
try {
field.set(obj, value);
} catch (IllegalAccessException e) {
logger.error("不可能拋出的異常" + e.getMessage());
}
}
/**
* 循環(huán)向上轉(zhuǎn)型, 獲取對象的DeclaredField, 并強(qiáng)制設(shè)置為可訪問.
* <p>
* 如向上轉(zhuǎn)型到Object仍無法找到, 返回null.
*/
public static Field getAccessibleField(final Object obj, final String fieldName) {
Assert.notNull(obj, "object不能為空");
Assert.hasText(fieldName, "fieldName");
for (Class<?> superClass = obj.getClass();
superClass != Object.class; superClass = superClass.getSuperclass()) {
try {
Field field = superClass.getDeclaredField(fieldName);
field.setAccessible(true);
return field;
} catch (NoSuchFieldException e) {//NOSONAR
// Field不在當(dāng)前類定義,繼續(xù)向上轉(zhuǎn)型
}
}
return null;
}
/**
* 直接調(diào)用對象方法, 無視private/protected修飾符.
* 用于一次性調(diào)用的情況.
*/
public static Object invokeMethod(final Object obj, final String methodName,
final Class<?>[] parameterTypes, final Object[] args) {
Method method = getAccessibleMethod(obj, methodName, parameterTypes);
if (method == null) {
throw new IllegalArgumentException(
"Could not find method [" + methodName + "] on target [" + obj + "]");
}
try {
return method.invoke(obj, args);
} catch (Exception e) {
throw convertReflectionExceptionToUnchecked(e);
}
}
/**
* 循環(huán)向上轉(zhuǎn)型, 獲取對象的DeclaredMethod,并強(qiáng)制設(shè)置為可訪問.
* 如向上轉(zhuǎn)型到Object仍無法找到, 返回null.
* <p>
* 用于方法需要被多次調(diào)用的情況. 先使用本函數(shù)先取得Method,然后調(diào)用Method.invoke(Object obj, Object... args)
*/
public static Method getAccessibleMethod(final Object obj, final String methodName,
final Class<?>... parameterTypes) {
Assert.notNull(obj, "object不能為空");
for (Class<?> superClass = obj.getClass();
superClass != Object.class; superClass = superClass.getSuperclass()) {
try {
Method method = superClass.getDeclaredMethod(methodName, parameterTypes);
method.setAccessible(true);
return method;
} catch (NoSuchMethodException e) {//NOSONAR
// Method不在當(dāng)前類定義,繼續(xù)向上轉(zhuǎn)型
}
}
return null;
}
/**
* 通過反射, 獲得Class定義中聲明的父類的泛型參數(shù)的類型.
* 如無法找到, 返回Object.class.
* eg.
* public UserDao extends HibernateDao<User>
*
* @param clazz The class to introspect
* @return the first generic declaration, or Object.class if cannot be determined
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public static <T> Class<T> getSuperClassGenricType(final Class clazz) {
return getSuperClassGenricType(clazz, 0);
}
/**
* 通過反射, 獲得Class定義中聲明的父類的泛型參數(shù)的類型.
* 如無法找到, 返回Object.class.
* <p>
* 如public UserDao extends HibernateDao<User,Long>
*
* @param clazz clazz The class to introspect
* @param index the Index of the generic ddeclaration,start from 0.
* @return the index generic declaration, or Object.class if cannot be determined
*/
@SuppressWarnings("rawtypes")
public static Class getSuperClassGenricType(final Class clazz, final int index) {
Type genType = clazz.getGenericSuperclass();
if (!(genType instanceof ParameterizedType)) {
logger.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
return Object.class;
}
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
if (index >= params.length || index < 0) {
logger.warn(
"Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: "
+ params.length);
return Object.class;
}
if (!(params[index] instanceof Class)) {
logger.warn(clazz.getSimpleName()
+ " not set the actual class on superclass generic parameter");
return Object.class;
}
return (Class) params[index];
}
/**
* 將反射時(shí)的checked exception轉(zhuǎn)換為unchecked exception.
*/
public static RuntimeException convertReflectionExceptionToUnchecked(Exception e) {
if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException
|| e instanceof NoSuchMethodException) {
return new IllegalArgumentException("Reflection Exception.", e);
} else if (e instanceof InvocationTargetException) {
return new RuntimeException("Reflection Exception.",
((InvocationTargetException) e).getTargetException());
} else if (e instanceof RuntimeException) {
return (RuntimeException) e;
}
return new RuntimeException("Unexpected Checked Exception.", e);
}
}
- 如何使用
首先我們的擁有一個(gè)實(shí)體類作為bean
例如我們的user類
class User implements Serializable{
private String userName;
private String passWord;
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;
}
}
我們需要些一個(gè)UserDao來實(shí)現(xiàn)User在mongo數(shù)據(jù)庫上的操作
@Repository
public class UserDAO extends BaseMongoDAOImpl<User> {
@Autowired
@Override
protected void setMongoTemplate(MongoTemplate mongoTemplate) {
this.mongoTemplate = mongoTemplate;
}
}
這時(shí)候我們只需要在想用到UserDAO的地方聲明這個(gè)屬性并注入進(jìn)去,就可以使用baseDao中的基礎(chǔ)方法了,如果想實(shí)現(xiàn)一些別的方法,可以自行進(jìn)行擴(kuò)展
<b>比如查詢一個(gè)用戶名是NB的人的時(shí)候,我們的就可以這么做</b>
Query query = new Query();
query.addCriteria(Criteria.where("userName").is("NB"));
User user = userDAO.findOne(query);
<b>又比如我用戶名為NB的人要把密碼改成123</b>
Query query = new Query();
query.addCriteria(Criteria.where("userName").is("NB"));
Update update = Update.update("passWord", "123");
userDAO.update(query, update);
參考鏈接
mongodb-java-driver基本用法
Spring整合- mongodb
Spring Data集成MongoDB訪問
spring集成mongodb封裝的簡單的CRUD
spring-data-mongo官方wiki
Spring Data MongoDB hello world 示例
Mongodb與spring集成(1)------配置
spring data mongodb更新或刪除子元素為數(shù)組的數(shù)據(jù)
spring集成mongodb封裝的簡單的CRUD