1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| 1、加载mongo配置信息 public abstract class AbstractMongoConfigure {
private String host, database, username, password; private int port; // Setter methods go here.. /* * Method that creates MongoDbFactory Common to both of the MongoDb * connections */ public MongoDbFactory mongoDbFactory() throws Exception { ServerAddress serverAddress = new ServerAddress(host, port); List<MongoCredential> mongoCredentialList = new ArrayList<>(); mongoCredentialList.add(MongoCredential.createScramSha1Credential(username, database, password.toCharArray())); return new SimpleMongoDbFactory(new MongoClient(serverAddress,mongoCredentialList), database); } /* * Factory method to create the MongoTemplate */ abstract public MongoTemplate getMongoTemplate() throws Exception; }
@Configuration @EnableMongoRepositories(basePackages = {"com.**.mapper.mg"},mongoTemplateRef = "mongoTemplate") @ComponentScan @ConfigurationProperties(prefix = "spring.datasource.mg") public class MongoMasterConfig extends AbstractMongoConfigure{
@Override @Bean("mongoTemplate") public MongoTemplate getMongoTemplate() throws Exception { return new MongoTemplate(mongoDbFactory()); }
} 2.1、编写Dao MongoTemplate模式
@Repository public class CmCableDetailRepo{
@Autowired private MongoTemplate mongoTemplate;
public Page<Cm_Cable> findByLevelAndName(String areacode, int level,String name,int pageNum, int pageSize){
PageRequest page = new PageRequest(pageNum, pageSize); Query query = new Query(); Criteria criteria = new Criteria(); criteria.and("areacode").regex("^"+areacode); if(level > -1){ criteria.and("cableSegment_level").is(level); } if(null != name && name.trim().length() > 0){ criteria.and("zh_label").regex(".*?"+name+".*"); } query.addCriteria(criteria); Long count = mongoTemplate.count(query, Cm_Cable.class);
List<Cm_Cable> list = mongoTemplate.find(query.with(page), Cm_Cable.class); return new PageImpl<Cm_Cable>(list, page, count); }
2.2、MongoRepository模式 @Repository public interface CmCableDetailMapper extends MongoRepository<Cm_Cable, String>{
}
|