在使用MongoTemplate操作mongoDB的时候,为了方便操作,我进行了二次封装
实现下面的目的, 封装基本的插入,修改,查询操作,具体的entity只需要简单的继承基础类加个@Repository就可以实现相关操作了
直接上代码:
import java.util.List;
public interface MongoBasicsDAO<T> {
void mongoSave(T obj);
void mongoDelete(String key,String value);
void mongoUpdate(String key,String value,T obj) throws Exception;
T mongoSingleTableSelete(String key,String value);
List<T> mongoPagingSelete(Integer pageIndex, Integer pageSize);
List<T> mongoCompositeSelete();
}
抽象实现:
import java.lang.reflect.ParameterizedType;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
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.start.framwork.mongo.util.MyClassUtil;
import java.lang.reflect.Type;
public abstract class MongoBasicsDAOImpl<T> implements MongoBasicsDAO<T>{
@Autowired
private MongoTemplate mongoTemplate;
private Class<T> obj;
/**
* 获取T的实际类型
*/
protected MongoBasicsDAOImpl() {
Type type = getClass().getGenericSuperclass();
Type trueType = ((ParameterizedType) type).getActualTypeArguments()[0];
this.obj = (Class<T>) trueType;
}
@Override
public void mongoSave(Object obj) {
// TODO Auto-generated method stub
mongoTemplate.save(obj);
}
@Override
public void mongoDelete(String key,String value) {
// TODO Auto-generated method stub
Query query = new Query(Criteria.where(key).is(value));
mongoTemplate.remove(query,obj);
}
@Override
public void mongoUpdate(String key,String value,Object o) throws Exception {
Query query = new Query(Criteria.where(key).is(value));
Update update = new Update();
String[] field = MyClassUtil.getFieldName(o);
for(int j = 0; j < field.length; j++) {
Object v = MyClassUtil.getFieldValueByName(field[j],o);
//System.out.println(field[j]+"---"+v);
update.set(field[j], v);
}
mongoTemplate.updateFirst(query, update, obj);
}
@SuppressWarnings("unchecked")
@Override
public T mongoSingleTableSelete(String key,String value) {
// TODO Auto-generated method stub
Query query = new Query(Criteria.where(key).is(value));
Type t = this.getClass().getGenericSuperclass();
return (T) mongoTemplate.findOne(query, obj);
}
@Override
public List<T> mongoPagingSelete(Integer pageIndex, Integer pageSize) {
// TODO Auto-generated method stub
Query query = new Query();
//Pageable pageable = new PageRequest(pageIndex ,pageSize);
Pageable pageable = PageRequest.of(pageIndex ,pageSize);
query.with(pageable);
return (List<T>) mongoTemplate.find(query, obj);
}
@Override
public List mongoCompositeSelete() {
// TODO Auto-generated method stub
return null;
}
}
具体的Dao类:
import org.springframework.stereotype.Repository;
import com.start.framwork.mongo.dao.MongoBasicsDAOImpl;
import com.start.framwork.mongo.eneity.Order;
@Repository
public class OrderDao extends MongoBasicsDAOImpl<Order> {
}
在进行update对象封装的时候,使用了反射的方式
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
public class MyClassUtil {
public static String[] getFieldName(Object o) {
Field[] declaredFields = o.getClass().getDeclaredFields();
String[] fieldNamStrings = new String[declaredFields.length];
for (int i = 0; i < fieldNamStrings.length; i++) {
fieldNamStrings[i] = declaredFields[i].getName();
}
return fieldNamStrings;
}
public static Object getFieldValueByName(String name, Object o) throws IllegalAccessException {
String firstletter = name.substring(0, 1).toUpperCase();
String getter = "get" + firstletter + name.substring(1);
Method method;
Object value;
try {
method = o.getClass().getMethod(getter, new Class[] {});
value = method.invoke(o);
return value;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* 根据属性,获取get方法
*
* @param ob 对象
* @param name 属性名
* @return
* @throws Exception
*/
public static Object getGetMethod(Object ob, String name) throws Exception {
Method[] m = ob.getClass().getMethods();
for (int i = 0; i < m.length; i++) {
if (("get" + name).toLowerCase().equals(m[i].getName().toLowerCase())) {
return m[i].invoke(ob);
}
}
return null;
}
/**
* 根据属性,拿到set方法,并把值set到对象中
*
* @param obj 对象
* @param clazz 对象的class
* @param fileName 需要设置值得属性
* @param typeClass
* @param value
*/
public static void setValue(Object obj, Class<?> clazz, String filedName, Class<?> typeClass, Object value) {
filedName = removeLine(filedName);
String methodName = "set" + filedName.substring(0, 1).toUpperCase() + filedName.substring(1);
try {
Method method = clazz.getDeclaredMethod(methodName, new Class[] { typeClass });
method.invoke(obj, new Object[] { getClassTypeValue(typeClass, value) });
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* 处理字符串 如: abc_dex ---> abcDex
*
* @param str
* @return
*/
public static String removeLine(String str) {
if (null != str && str.contains("_")) {
int i = str.indexOf("_");
char ch = str.charAt(i + 1);
char newCh = (ch + "").substring(0, 1).toUpperCase().toCharArray()[0];
String newStr = str.replace(str.charAt(i + 1), newCh);
String newStr2 = newStr.replace("_", "");
return newStr2;
}
return str;
}
/**
* 通过class类型获取获取对应类型的值
*
* @param typeClass class类型
* @param value 值
* @return Object
*/
private static Object getClassTypeValue(Class<?> typeClass, Object value) {
if (typeClass == int.class || value instanceof Integer) {
if (null == value) {
return 0;
}
return value;
} else if (typeClass == short.class) {
if (null == value) {
return 0;
}
return value;
} else if (typeClass == byte.class) {
if (null == value) {
return 0;
}
return value;
} else if (typeClass == double.class) {
if (null == value) {
return 0;
}
return value;
} else if (typeClass == long.class) {
if (null == value) {
return 0;
}
return value;
} else if (typeClass == String.class) {
if (null == value) {
return "";
}
return value;
} else if (typeClass == boolean.class) {
if (null == value) {
return true;
}
return value;
} else if (typeClass == BigDecimal.class) {
if (null == value) {
return new BigDecimal(0);
}
return new BigDecimal(value + "");
} else {
return typeClass.cast(value);
}
}
}
测试方法:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.start.framwork.mongo.eneity.Order;
import com.start.framwork.mongo.eneity.User;
import com.start.framwork.mongo.service.impl.MongoService;
@RunWith(SpringRunner.class)
@SpringBootTest
public class Test1 {
@Autowired
private MongoService mongoService;
@Test
public void saveTest() {
Order order = new Order();
order.setId("1");
order.setName("test");
order.setProductNmae("product-001");
order.setQuantity(2);
mongoService.mongoSaveOrder(order);
}
@Test
public void selectTest() {
System.out.println(mongoService.seleteUser("name", "张三"));
}
@Test
public void pselectTest() {
System.out.println(mongoService.pagingSeleteUser(2, 2));
}
@Test
public void updateTest() throws Exception {
User user = new User();
user.setName("阿Y");
user.setAge(179);
user.setClassId("2");
user.setSex("F");
mongoService.updateUser("name","阿Y",user);
}
}