Sring-data-mongo框架
1、定义:基于Spring开发的一个简化MongoAPI操作的java框架,其使用方式与spring一致
2、Spring-Data-Mongo简化的MongoAPI操作内容
a、重复性的代码-----》如初始化
例:Mongo m=new Mongo(ip,port);
DB db=m.getDB("dbName");
DBCollection dbCollection=db.getCollection("collectionName");
(1)链接Mongo 、(2)获取数据库、(3)得到DBCollection
Sring的封装
<mongo:db-factory id="dbFactory" host="127.0.0.1" port="27017" dbname="baichi" />
id是spring固有属性,dbname是访问的数据库名称
b、简化MongoAPI的操作,提供了自动Mapper的方式
User{ DBObject{
private String name; name
private String pwd; --------------相当于封装了----------> pwd
} }
c、提供了MongoTemplate简化DAO层CURD的操作
3、spring-data-mongo的开发步骤
a、搭建开发环境
(1)引入spring框架的相关jar包
(2)MongoDriver的jar包
(3)springDataMongo的jar包
配置文件spring.xml,Mongo的schema
xmls:context="http://www.springframework.org/scheme/context"
xmls:mongo="http://www.springframework.org/scheme/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/spring-beans-3.0/xsd"
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
b、配置MongoDB的链接信息
<mongo:db-factory id="dbFacttory" host="127.0.0.1" port="27017" dbname="baichi" />
4、spring-Data-Mongo的Mapper开发步骤
a、在实体类Customer中引入注解表明转换方式
@Document //文档
public class Customer{
@Id
@Indexed(unigue=true)
private String id;
@Field("customer_name")//MongoDB中的key
private String name; //将name转换成为Json类型的Customer_name
//作为值转换,**由于mongoDb中的一个键也是"password"和它一样的字符串,所以不用写@Field("password")注解
private String password;
/**
*提供set/get和toString方法
*/
}
b、在spring配置文件中声明转换器MongoConverter
<mongo:mapping-converter id="converter"(标识) db-factory-ref="dbFactory"(dbfactory的id)
base-package="com.baichi.entity"(实体类路径)>
</mongo:mapping-converter>
c、注入MongoConverter调用方法就行转换MongoConverter.read()方法把DBObject的内容写入Entity中
d、导入架包
commons-logging-1.1.1.jar、log4j-1.2.16.jar、mongo-java-driver-2.9.3.jar、slf4j-api-1.6.1.jar、slf4j-log4j-1.6.1.jar
spring-beans-3.2.9-RELEASE.jar、spring-context-3.2.9-RELEASE.jar、spring-core-3.2.9-RELEASE.jar、spring-data-commons-core-RELEASE.jar
spring-data-mongodb-1.0.0-RELEASE.jar、spring-data-mongodb-log4j-RELEASE.jar、
spring-expression-3.2.9-RELEASE.jar、spring-test-3.2.9-RELEASE.jar、spring-tx-3.2.9-RELEASE.jar
e、测试类
@RunWith(SpringJUnit4ClassRunner.calss)
@ContextConfiguration("/applicationContext.xml")
public class testConverter{
@Autowrired
private MongoConverter converter;//转换器
//测试类(一)
@Test
public void testEntity2DBObject(){
Customer c=new Customer();//实体类
c.setId(".");
c.setName("suns");
c.setPassword("123456");
DBObject dbObject=new BasicDBObject();
converter.writer.println("Entity转换成Json的值:"+dbObject);
}
//测试类(二)
@Test
public void testDBObject2Entity(){
DBObject dbObject=new new BasicDBObject();
dbObject.put("_id",10);
dbObject.put("“customer_name”,"xiaobei");
dbObject.put("password","123456");
Customer c=converter.read(Customer.class,dbObject);
System.out.println("打印转换成为实体类:"+c);
}
}