spring mongdb体验
package
com.duxiu.mongodb;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.convert.MongoTypeMapper;
public class MongoConverterEnhanceFactoryBean implements FactoryBean < MappingMongoConverter > {
private MappingMongoConverter mongoConverter;
public void setMongoConverter(MappingMongoConverter mongoConverter) {
this .mongoConverter = mongoConverter;
}
@Override
public MappingMongoConverter getObject() throws Exception {
MongoTypeMapper typeMapper = new DefaultMongoTypeMapper( null );
mongoConverter.setTypeMapper(typeMapper);
return mongoConverter;
}
@Override
public Class <?> getObjectType() {
return MappingMongoConverter. class ;
}
@Override
public boolean isSingleton() {
return true ;
}
}
import org.springframework.beans.factory.FactoryBean;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.convert.MongoTypeMapper;
public class MongoConverterEnhanceFactoryBean implements FactoryBean < MappingMongoConverter > {
private MappingMongoConverter mongoConverter;
public void setMongoConverter(MappingMongoConverter mongoConverter) {
this .mongoConverter = mongoConverter;
}
@Override
public MappingMongoConverter getObject() throws Exception {
MongoTypeMapper typeMapper = new DefaultMongoTypeMapper( null );
mongoConverter.setTypeMapper(typeMapper);
return mongoConverter;
}
@Override
public Class <?> getObjectType() {
return MappingMongoConverter. class ;
}
@Override
public boolean isSingleton() {
return true ;
}
}
package
com.duxiu.mongodb.po;
import java.io.Serializable;
@Document(collection = " userDoc " )
@CompoundIndexes({ @CompoundIndex(def = " {areaid:1} " , name = " areaidName " ),
@CompoundIndex(def = " {areaid:1,schoolid:1} " , name = " areaschool " ) })
public class User implements Serializable {
private static final long serialVersionUID = 1393678160766939903L ;
@Id
@Indexed
private Integer areaid;
@Indexed
private Integer schoolid;
private Integer userid;
private String phoneNum;
private String userName;
private Integer count;
public User() {
}
public User(Integer areaid, Integer schoolid, Integer userid, String phoneNum, String userName) {
this .areaid = areaid;
this .schoolid = schoolid;
this .userid = userid;
this .phoneNum = phoneNum;
this .userName = userName;
}
public Integer getAreaid() {
return areaid;
}
public void setAreaid(Integer areaid) {
this .areaid = areaid;
}
public Integer getSchoolid() {
return schoolid;
}
public void setSchoolid(Integer schoolid) {
this .schoolid = schoolid;
}
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this .userid = userid;
}
public String getPhoneNum() {
return phoneNum;
}
public void setPhoneNum(String phoneNum) {
this .phoneNum = phoneNum;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this .userName = userName;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this .count = count;
}
}
import java.io.Serializable;
@Document(collection = " userDoc " )
@CompoundIndexes({ @CompoundIndex(def = " {areaid:1} " , name = " areaidName " ),
@CompoundIndex(def = " {areaid:1,schoolid:1} " , name = " areaschool " ) })
public class User implements Serializable {
private static final long serialVersionUID = 1393678160766939903L ;
@Id
@Indexed
private Integer areaid;
@Indexed
private Integer schoolid;
private Integer userid;
private String phoneNum;
private String userName;
private Integer count;
public User() {
}
public User(Integer areaid, Integer schoolid, Integer userid, String phoneNum, String userName) {
this .areaid = areaid;
this .schoolid = schoolid;
this .userid = userid;
this .phoneNum = phoneNum;
this .userName = userName;
}
public Integer getAreaid() {
return areaid;
}
public void setAreaid(Integer areaid) {
this .areaid = areaid;
}
public Integer getSchoolid() {
return schoolid;
}
public void setSchoolid(Integer schoolid) {
this .schoolid = schoolid;
}
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this .userid = userid;
}
public String getPhoneNum() {
return phoneNum;
}
public void setPhoneNum(String phoneNum) {
this .phoneNum = phoneNum;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this .userName = userName;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this .count = count;
}
}
package
com.duxiu.mongodb;
import org.springframework.data.domain.Page;
@RepositoryDefinition(idClass = Integer. class , domainClass = User. class )
public interface MyRepository {
public Page < User > findByUserid( int userid, Pageable pageable);
}
import org.springframework.data.domain.Page;
@RepositoryDefinition(idClass = Integer. class , domainClass = User. class )
public interface MyRepository {
public Page < User > findByUserid( int userid, Pageable pageable);
}
package
com.duxiu.mongodb;
import org.springframework.data.domain.Page;
public interface UserRepository extends MongoRepository < User, Integer > {
public Page < User > findBySchoolidAndUserid( int schoolid, int userid, Pageable pageable);
}
import org.springframework.data.domain.Page;
public interface UserRepository extends MongoRepository < User, Integer > {
public Page < User > findBySchoolidAndUserid( int schoolid, int userid, Pageable pageable);
}
package
com.duxiu.mongodb;
import javax.annotation.Resource;
import org.junit.Test;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import com.duxiu.mongodb.po.User;
@org.springframework.data.convert.WritingConverter
@ContextConfiguration(locations = { " classpath:/applicationContext.xml " })
public class MongoDBTest extends AbstractJUnit4SpringContextTests {
@Resource(name = " mongoTemplate " )
private MongoOperations mongoOperation;
@Resource
private UserRepository userRepository;
@Resource
private MyRepository userRepository1;
@Test
public void testaa() {
// mongoOperation.dropCollection(User.class);
User user1 = new User( 1 , 1 , 1 , " 13552674285 " , " simone " );
User user2 = new User( 1 , 2 , 2 , " 13552674287 " , " simone2 " );
User user3 = new User( 3 , 2 , 3 , " 13552674282 " , " simone3 " );
// mongoOperation.save(user1);
// mongoOperation.save(user2);
mongoOperation.save(user3);
// List<User> userList = mongoOperation.findAll(User.class);
// for (User u : userList) {
// System.out.println(u.getUserid());
// }
//
// System.out.println("=======================");
//
// List<User> userList = mongoOperation.find(new Query(Criteria.where("userid").is(3)), User.class);
// for (User u : userList) {
// System.out.println(u.getUserid());
// }
// GroupBy groupBy = GroupBy.key("userid");
// groupBy.initialDocument("{count: 0}");
// groupBy.reduceFunction("function(obj,prev){ prev.count++;}");
//
// GroupByResults<User> groupByResults = mongoOperation.group(mongoOperation.getCollectionName(User.class),
// groupBy, User.class);
// Iterator<User> iu = groupByResults.iterator();
// while (iu.hasNext()) {
// User u = iu.next();
// System.out.println(u.getCount());
// }
// System.out.println(groupByResults.getRawResults().toString());
//
// List<IndexInfo> list = mongoOperation.indexOps(User.class).getIndexInfo();
// for (IndexInfo i : list) {
// System.out.println(i.getName());
// }
}
@Test
public void testbb() {
PageRequest pageRequest = new PageRequest( 0 , 10 );
Page < User > user = userRepository.findBySchoolidAndUserid( 2 , 3 , pageRequest);
System.out.println(user.getContent());
System.out.println( " ======================= " );
User user2 = new User( 1 , 2 , 2 , " 13552674287 " , " simone2 " );
User u = userRepository.save(user2);
System.out.println(u.getUserid());
System.out.println( " ======================= " );
user = userRepository1.findByUserid( 3 , pageRequest);
System.out.println(user.getContent());
}
}
import javax.annotation.Resource;
import org.junit.Test;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import com.duxiu.mongodb.po.User;
@org.springframework.data.convert.WritingConverter
@ContextConfiguration(locations = { " classpath:/applicationContext.xml " })
public class MongoDBTest extends AbstractJUnit4SpringContextTests {
@Resource(name = " mongoTemplate " )
private MongoOperations mongoOperation;
@Resource
private UserRepository userRepository;
@Resource
private MyRepository userRepository1;
@Test
public void testaa() {
// mongoOperation.dropCollection(User.class);
User user1 = new User( 1 , 1 , 1 , " 13552674285 " , " simone " );
User user2 = new User( 1 , 2 , 2 , " 13552674287 " , " simone2 " );
User user3 = new User( 3 , 2 , 3 , " 13552674282 " , " simone3 " );
// mongoOperation.save(user1);
// mongoOperation.save(user2);
mongoOperation.save(user3);
// List<User> userList = mongoOperation.findAll(User.class);
// for (User u : userList) {
// System.out.println(u.getUserid());
// }
//
// System.out.println("=======================");
//
// List<User> userList = mongoOperation.find(new Query(Criteria.where("userid").is(3)), User.class);
// for (User u : userList) {
// System.out.println(u.getUserid());
// }
// GroupBy groupBy = GroupBy.key("userid");
// groupBy.initialDocument("{count: 0}");
// groupBy.reduceFunction("function(obj,prev){ prev.count++;}");
//
// GroupByResults<User> groupByResults = mongoOperation.group(mongoOperation.getCollectionName(User.class),
// groupBy, User.class);
// Iterator<User> iu = groupByResults.iterator();
// while (iu.hasNext()) {
// User u = iu.next();
// System.out.println(u.getCount());
// }
// System.out.println(groupByResults.getRawResults().toString());
//
// List<IndexInfo> list = mongoOperation.indexOps(User.class).getIndexInfo();
// for (IndexInfo i : list) {
// System.out.println(i.getName());
// }
}
@Test
public void testbb() {
PageRequest pageRequest = new PageRequest( 0 , 10 );
Page < User > user = userRepository.findBySchoolidAndUserid( 2 , 3 , pageRequest);
System.out.println(user.getContent());
System.out.println( " ======================= " );
User user2 = new User( 1 , 2 , 2 , " 13552674287 " , " simone2 " );
User u = userRepository.save(user2);
System.out.println(u.getUserid());
System.out.println( " ======================= " );
user = userRepository1.findByUserid( 3 , pageRequest);
System.out.println(user.getContent());
}
}
<?
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:jee ="http://www.springframework.org/schema/jee"
xmlns:tx ="http://www.springframework.org/schema/tx" 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/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd" >
< mongo:mongo host ="localhost" port ="27017" >
< mongo:options connections-per-host ="8"
threads-allowed-to-block-for-connection-multiplier ="4"
connect-timeout ="1000" max-wait-time ="1500" auto-connect-retry ="true"
socket-keep-alive ="true" socket-timeout ="1500" slave-ok ="true"
write-number ="1" write-timeout ="0" write-fsync ="true" />
</ mongo:mongo >
<!-- mongo的工厂,通过它来取得mongo实例,dbname为mongodb的数据库名,没有的话会自动创建 -->
< mongo:db-factory dbname ="testDB" mongo-ref ="mongo" />
< mongo:mapping-converter />
< bean id ="simpleMongoConverter" class ="com.duxiu.mongodb.MongoConverterEnhanceFactoryBean" >
< property name ="mongoConverter" ref ="mappingConverter" />
</ bean >
< bean id ="mongoTemplate" class ="org.springframework.data.mongodb.core.MongoTemplate" >
< constructor-arg name ="mongoDbFactory" ref ="mongoDbFactory" />
< constructor-arg name ="mongoConverter" ref ="simpleMongoConverter" />
</ bean >
<!-- mongodb bean的仓库目录,会自动扫描扩展了MongoRepository接口的接口进行注入 -->
< mongo:repositories base-package ="com.duxiu.mongodb" />
</ beans >
< beans xmlns ="http://www.springframework.org/schema/beans"
xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee ="http://www.springframework.org/schema/jee"
xmlns:tx ="http://www.springframework.org/schema/tx" 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/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd" >
< mongo:mongo host ="localhost" port ="27017" >
< mongo:options connections-per-host ="8"
threads-allowed-to-block-for-connection-multiplier ="4"
connect-timeout ="1000" max-wait-time ="1500" auto-connect-retry ="true"
socket-keep-alive ="true" socket-timeout ="1500" slave-ok ="true"
write-number ="1" write-timeout ="0" write-fsync ="true" />
</ mongo:mongo >
<!-- mongo的工厂,通过它来取得mongo实例,dbname为mongodb的数据库名,没有的话会自动创建 -->
< mongo:db-factory dbname ="testDB" mongo-ref ="mongo" />
< mongo:mapping-converter />
< bean id ="simpleMongoConverter" class ="com.duxiu.mongodb.MongoConverterEnhanceFactoryBean" >
< property name ="mongoConverter" ref ="mappingConverter" />
</ bean >
< bean id ="mongoTemplate" class ="org.springframework.data.mongodb.core.MongoTemplate" >
< constructor-arg name ="mongoDbFactory" ref ="mongoDbFactory" />
< constructor-arg name ="mongoConverter" ref ="simpleMongoConverter" />
</ bean >
<!-- mongodb bean的仓库目录,会自动扫描扩展了MongoRepository接口的接口进行注入 -->
< mongo:repositories base-package ="com.duxiu.mongodb" />
</ beans >
# Output pattern : date
[
thread
]
priority category - message
log4j.rootLogger = DEBUG , Console , RollingFile
#Console
log4j.appender.Console = org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern = %d [ %t ] MobileLibHomePage %-5p [ %C.%M:%L ] - %m%n
#RollingFile
log4j.appender.RollingFile = org.apache.log4j.DailyRollingFileAppender
log4j.appender.RollingFile.File = logs/mini-web.log
log4j.appender.RollingFile.layout = org.apache.log4j.PatternLayout
log4j.appender.RollingFile.layout.ConversionPattern = %d [ %t ] MobileLibHomePage %-5p [ %C.%M:%L ] - %m%n
#Project defalult level
log4j.logger.org.springframework.data = DEBUG
log4j.rootLogger = DEBUG , Console , RollingFile
#Console
log4j.appender.Console = org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern = %d [ %t ] MobileLibHomePage %-5p [ %C.%M:%L ] - %m%n
#RollingFile
log4j.appender.RollingFile = org.apache.log4j.DailyRollingFileAppender
log4j.appender.RollingFile.File = logs/mini-web.log
log4j.appender.RollingFile.layout = org.apache.log4j.PatternLayout
log4j.appender.RollingFile.layout.ConversionPattern = %d [ %t ] MobileLibHomePage %-5p [ %C.%M:%L ] - %m%n
#Project defalult level
log4j.logger.org.springframework.data = DEBUG