spring与mongodb的泛型Dao整合

在前人的基础上,进行了spring与mongodb的初期整合,如果有什么不对的地方,请指正

Maven的pom.xml(部分jar多余,可考虑删除)


  4.0.0
  springForMongo
  springForMongo
  0.0.1-SNAPSHOT
  war
  
  
  
		
		3.2.4.RELEASE
		
		1.6.6
		1.2.9
	
	
		
		
		
			org.springframework
			spring-core
			${spring.version}
		

		
			org.springframework
			spring-web
			${spring.version}
		

		
			org.springframework
			spring-oxm
			${spring.version}
		

		
			org.springframework
			spring-tx
			${spring.version}
		

		
			org.springframework
			spring-jdbc
			${spring.version}
		

		
			org.springframework
			spring-webmvc
			${spring.version}
		

		
			org.springframework
			spring-aop
			${spring.version}
		

		
			org.springframework
			spring-context-support
			${spring.version}
		


		
			org.springframework
			spring-test
			${spring.version}
		
		
		
			javax.servlet
			servlet-api
			2.5
			jar
			provided
		
		
			org.mongodb
			mongo-java-driver
			2.10.1
			jar
			compile
		
		
			org.springframework.data
			spring-data-mongodb
			1.2.1.RELEASE
			jar
			compile
		
		
			org.springframework.data
			spring-data-mongodb-cross-store
			1.2.1.RELEASE
			jar
			compile
		
		
			org.springframework.data
			spring-data-mongodb-log4j
			1.2.1.RELEASE
			jar
			compile
		
		
		
			junit
			junit
			4.11
			test
		

		
		
		
			log4j
			log4j
			${log4j.version}
		
		
			org.slf4j
			slf4j-api
			${slf4j.version}
		
		
			org.slf4j
			slf4j-log4j12
			${slf4j.version}
		
		
			org.apache.commons
			commons-lang3
			3.3.2
		
		
	
  
    
      
        maven-war-plugin
      
      
        maven-compiler-plugin
        
          1.6
          1.6
        
      
    
  

 spring.xml

  
  
  
      
  
      
  
      
      
  
      
      
          
      
  
      
      
  
      
      
  
      
  
  

 BaseDaoI

@Transactional
public interface BaseDaoI {
	

	    public abstract void _test();  
	  
	    public abstract void createCollection(T object);  
	  
	    public abstract List findList(int skip, int limit);  
	  
	    public abstract T findOneByItems(Map params);  
	  
	    public abstract void insert(T t);  
	  
	    public abstract void update(String id,Map params,T t);
	    
	    public abstract long count(Map params);
	    
	    public abstract List findByItems(Map params);

		public abstract List findListByPageAndItems(int skip, int rows, Map params);
		
		public abstract void deleteById(String id);
		
		public abstract void saveFile(File file,String fileUrl);
		
		public abstract GridFSDBFile retrieveFileOne(String filename); 
}

 StaffDaoI

import org.springframework.transaction.annotation.Transactional;

import com.mongodb.model.Staff;

@Transactional
public interface StaffDaoI extends BaseDaoI {

}

 BaseDaoImpl.class

import java.io.File;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
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 org.springframework.stereotype.Repository;

import com.mongodb.DB;
import com.mongodb.dao.BaseDaoI;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;

@Repository
public class BaseDaoImpl implements BaseDaoI {
	
	public static final Logger logger = LoggerFactory.getLogger(BaseDaoImpl.class);
	
	public static final String FILEURL="imgRespository"; 

	@Autowired
	private MongoTemplate mongoTemplate;
	
	private Class clz;
	
	public Class getClz() {
		if(clz==null) {
			//获取泛型的Class对象
			clz = ((Class)
					(((ParameterizedType)(this.getClass().getGenericSuperclass())).getActualTypeArguments()[0]));
		}
		return clz;
	}
	public BaseDaoImpl() {
		
	}

	@Override
	public void _test() {
		Set colls = this.mongoTemplate.getCollectionNames();
		for (String coll : colls) {
			logger.info("CollectionName=" + coll);
		}
		DB db = this.mongoTemplate.getDb();
		logger.info("db=" + db.toString());
	}

	@Override
	public void createCollection(T object) {
		if (!this.mongoTemplate.collectionExists(getClz())) {
			this.mongoTemplate.createCollection(getClz());
		}
		
	}

	@Override
	public List findList(int skip, int limit) {
		Query query = new Query();
		query.with(new Sort(new Order(Direction.ASC, "_id")));
		query.skip(skip).limit(limit);
		return (List)this.mongoTemplate.find(query, getClz());
	}

	@Override
	public T findOneByItems(Map params) {
		Query query = new Query();
		if ((params != null) && (!(params.isEmpty()))) {
		      for (String key : params.keySet()) {
		    	  query.addCriteria(new Criteria(key).is(params.get(key)));
		      }
		 }
		return (T)mongoTemplate.findOne(query, getClz());
	}

	@Override
	public void insert(T t) {
		this.mongoTemplate.insert(t);
	}


	@Override
	public long count(Map params) {
		Query query = new Query();
		if ((params != null) && (!(params.isEmpty()))) {
		      for (String key : params.keySet()) {
		    	  query.addCriteria(new Criteria(key).is(params.get(key)));
		      }
		    }
		return (long)mongoTemplate.find(query, getClz()).size();
	}

	@Override
	public List findByItems(Map params) {
		Query query = new Query();
		if ((params != null) && (!(params.isEmpty()))) {
		      for (String key : params.keySet()) {
		    	  query.addCriteria(new Criteria(key).is(params.get(key)));
		      }
		    }
		return (List)this.mongoTemplate.find(query, getClz());
	}

	@Override
	public List findListByPageAndItems(int skip, int rows,
			Map params) {
		Query query = new Query();
		if ((params != null) && (!(params.isEmpty()))) {
		      for (String key : params.keySet()) {
		    	  query.addCriteria(new Criteria(key).is(params.get(key)));
		      }
		 }
		query.skip(skip).limit(rows);
		return (List)this.mongoTemplate.find(query, getClz());
	}

	@Override
	public void update(String id, Map params,T t) {
		Query query = new Query();
		query.addCriteria(new Criteria("_id").is(id));
		Update update = new Update();
		if ((params != null) && (!(params.isEmpty()))) {
		      for (String key : params.keySet()) {
		    	  update.set(key, params.get(key));
		      }
		 }
		this.mongoTemplate.updateFirst(query, update,getClz());
	}
	@Override
	public void deleteById(String id) {
		mongoTemplate.remove(new Query(Criteria.where("_id").is(id)), getClz());
	}
	
	
	@Override
	public void saveFile(File file, String fileUrl) {
		  try {  
	            DB db = mongoTemplate.getDb();  
	            GridFS fs = new GridFS(db, FILEURL);  
	            GridFSInputFile inputFile = fs.createFile(file);  
	            inputFile.setFilename(fileUrl);  
	            inputFile.setContentType(fileUrl.substring(fileUrl.lastIndexOf(".")));  
	            inputFile.save();  
	        } catch (IOException e) {  
	            e.printStackTrace();  
	        } 
	}
	
	@Override
	public GridFSDBFile retrieveFileOne(String filename) {
		 try {  
	            DB db = mongoTemplate.getDb();  
	            // 获取fs的根节点  
	            GridFS gridFS = new GridFS(db, FILEURL);  
	            GridFSDBFile dbfile = gridFS.findOne(filename);  
	            if (dbfile != null) {  
	                return dbfile;  
	            }  
	        } catch (Exception e) {  
	        	e.printStackTrace();  
	        }  
	        return null; 
	}

}

 StaffDaoImpl

import org.springframework.stereotype.Repository;

import com.mongodb.dao.StaffDaoI;
import com.mongodb.model.Staff;

@Repository
public class StaffDaoImpl extends BaseDaoImpl implements StaffDaoI{

}

 Entity Staff.java(@Id是import org.springframework.data.annotation.Id)

@Document(collection = "staff") 
public class Staff {

	@Id
	private String id;
	
	/**
	 * 姓名
	 */
	private String name;
	
	/**
	 * 邮箱
	 */
	private String[] email;
	
	/**
	 * 出身日期
	 */
	private Date birthday;
	
	/**
	 * 部门名称
	 */
	private String department;
	
	/**
	 * 毕业学校
	 */
	private String school;
	
	/**
	 * 现居地
	 */
	private String location;
	
	/**
	 * 年龄
	 */
	private int age;
	
	/**
	 * 员工评论
	 */
	private List comments;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String[] getEmail() {
		return email;
	}

	public void setEmail(String[] email) {
		this.email = email;
	}

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}


	public String getDepartment() {
		return department;
	}

	public void setDepartment(String department) {
		this.department = department;
	}

	public String getSchool() {
		return school;
	}

	public void setSchool(String school) {
		this.school = school;
	}

	public String getLocation() {
		return location;
	}

	public void setLocation(String location) {
		this.location = location;
	}

	public List getComments() {
		return comments;
	}

	public void setComments(List comments) {
		this.comments = comments;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "Staff [id=" + id + ", name=" + name + ", email="
				+ Arrays.toString(email) + ", birthday=" + birthday
				+ ", department=" + department + ", school=" + school
				+ ", location=" + location + ", age=" + age + ", comments="
				+ comments + "]";
	}
}

 Comment.class(员工评论与员工一对多)

@Document
public class Comment {

	@Id
	private String id;

	/**
	 * 评论内容
	 */
	private String content;

	/**
	 * 评论日期
	 */
	private Date conDate;
	
	public Comment() {
		
	}
	
	public Comment(String content, Date conDate) {
		this.content = content;
		this.conDate = conDate;
	}
	
	

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public Date getConDate() {
		return conDate;
	}

	public void setConDate(Date conDate) {
		this.conDate = conDate;
	}

}

 测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring.xml" })
public class TestMongoDb {

	@Autowired
	public StaffDaoI staffDao;

	/**
	 * 在数据库test_mongodb中创建一个collection集合staff
	 */
	@Test
	public void test1() {
		Staff staff = new Staff();
		staffDao.createCollection(staff);
	}
	
	/**
	 * 保存一条数据
	 */
	@Test
	public void test2() {
		Staff staff = new Staff();
		staff.setName("chenjunfeng");
		staff.setAge(35);
		staff.setDepartment("1-4-4");
		staff.setLocation("sanshanjie");
		staff.setBirthday(new Date());
		staff.setId("000111");
		staff.setSchool("nanjingdaxue");
		Comment comment=new Comment();
		comment.setConDate(new Date());
		comment.setContent("good leader");
		Comment comment1=new Comment();
		comment.setConDate(new Date());
		comment.setContent("a very good leader");
		List comments=new ArrayList();
		comments.add(comment);
		comments.add(comment1);
		staff.setComments(comments);
		staff.setEmail(new String[]{"[email protected]","[email protected]"});
		staffDao.insert(staff);
	}
	
	/**
	 * 根据检索条件返回检索个数
	 */
	@Test
	public void test3() {
		Map params=new HashMap();
		params.put("age", 35);
		System.out.println(staffDao.count(params));
	}
	
	/**
	 * 根据条件返回数据的集合
	 */
	@Test
	public void test5() {
		Map params=new HashMap();
		params.put("age", 35);
		System.out.println(staffDao.findByItems(params).get(0).toString());
	}
	
	/**
	 * 存储图片
	 */
	@Test
	public void test6() {
		 File file=new File("D:\\cloud.jpg");
		 String fileUrl="cloud.jpg";
		 staffDao.saveFile(file, fileUrl);
	}
	
	/**
	 * 	取出图片
	 * @throws IOException
	 */
	@Test
	public void test7() throws IOException {
		 String fileUrl="cloud.jpg";
		 GridFSDBFile file=staffDao.retrieveFileOne(fileUrl);
		 System.out.println(file.getId());
		 System.out.println(file.getContentType());
		 System.out.println(file.getChunkSize());
		 file.writeTo(new File("E:\\cloud.jpg"));
	}
	
	//TODO
	//分页就不做测试了,有兴趣的可以尝试一下
}

 有不对的可以指正一下,或者dao层实现方式有不妥的地方请提出

你可能感兴趣的:(database)