spring与mongodb的泛型Dao整合

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

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

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>springForMongo</groupId>
  <artifactId>springForMongo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <name/>
  <description/>
  <properties>
		<!-- spring版本号 -->
		<spring.version>3.2.4.RELEASE</spring.version>
		<!-- log4j日志文件管理包版本 -->
		<slf4j.version>1.6.6</slf4j.version>
		<log4j.version>1.2.9</log4j.version>
	</properties>
	<dependencies>
		<!-- spring核心包 -->
		<!-- springframe start -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-oxm</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${spring.version}</version>
		</dependency>


		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<!-- springframe end -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<type>jar</type>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.mongodb</groupId>
			<artifactId>mongo-java-driver</artifactId>
			<version>2.10.1</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-mongodb</artifactId>
			<version>1.2.1.RELEASE</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-mongodb-cross-store</artifactId>
			<version>1.2.1.RELEASE</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-mongodb-log4j</artifactId>
			<version>1.2.1.RELEASE</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<!-- junit测试包 -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>

		<!-- 日志文件管理包 -->
		<!-- log start -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>${log4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.3.2</version>
		</dependency>
		<!-- log end -->
	</dependencies>
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
      </plugin>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.6</source>
          <target>1.6</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

 spring.xml

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:mongo="http://www.springframework.org/schema/data/mongo"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
        http://www.springframework.org/schema/data/mongo       
        http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd   
        http://www.springframework.org/schema/context  
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
  
    <context:component-scan base-package="com.mongodb" />  
  
    <mongo:mongo host="127.0.0.1" port="27017" />  
  
    <!-- mongo的工厂,通过它来取得mongo实例,dbname为mongodb的数据库名,没有的话会自动创建 -->  
    <mongo:db-factory dbname="test_mongodb" mongo-ref="mongo" />  
  
    <!-- mongodb的主要操作对象,所有对mongodb的增删改查的操作都是通过它完成 -->  
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">  
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />  
    </bean>  
  
    <!-- 映射转换器,扫描back-package目录下的文件,根据注释,把它们作为mongodb的一个collection的映射 -->  
    <mongo:mapping-converter base-package="com.mongodb.model" />  
  
    <!-- mongodb bean的仓库目录,会自动扫描扩展了MongoRepository接口的接口进行注入 -->  
    <mongo:repositories base-package="com.mongodb.dao.impl" />  
  
    <context:annotation-config />  
  
</beans>  

 BaseDaoI

@Transactional
public interface BaseDaoI<T> {
	

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

		public abstract List<T> findListByPageAndItems(int skip, int rows, Map<String, Object> 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<Staff> {

}

 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<T> implements BaseDaoI<T> {
	
	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<String> 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<T> 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<T>)this.mongoTemplate.find(query, getClz());
	}

	@Override
	public T findOneByItems(Map<String, Object> 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<String, Object> 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<T> findByItems(Map<String, Object> 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<T>)this.mongoTemplate.find(query, getClz());
	}

	@Override
	public List<T> findListByPageAndItems(int skip, int rows,
			Map<String, Object> 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<T>)this.mongoTemplate.find(query, getClz());
	}

	@Override
	public void update(String id, Map<String, Object> 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<Staff> 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<Comment> 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<Comment> getComments() {
		return comments;
	}

	public void setComments(List<Comment> 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<Comment> comments=new ArrayList<Comment>();
		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<String,Object> params=new HashMap<String, Object>();
		params.put("age", 35);
		System.out.println(staffDao.count(params));
	}
	
	/**
	 * 根据条件返回数据的集合
	 */
	@Test
	public void test5() {
		Map<String,Object> params=new HashMap<String, Object>();
		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层实现方式有不妥的地方请提出

你可能感兴趣的:(spring与mongodb的泛型Dao整合)