Spring boot + Mongodb

mongodb的增刪改查

一、pom包配置

pom包裏面添加spring-boot-starter-data-mongodb包引用java

<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> </dependencies>

 

二、在application.properties中添加配置

spring.data.mongodb.uri=mongodb://user:pwd@localhost:27017/test

多個IP集羣能夠採用如下配置:spring

spring.data.mongodb.uri=mongodb://user:pwd@ip1:port1,ip2:port2/database

 

三、建立數據實體

public class UserEntity implements Serializable { private static final long serialVersionUID = -3258839839160856613L; private Long id; private String userName; private String passWord; //getter、setter省略 }

 

四、建立實體dao的增刪改查操做

dao層實現了UserEntity對象的增刪改查mongodb

@Component public class UserDaoImpl implements UserDao { @Autowired private MongoTemplate mongoTemplate; /**  * 建立對象  * @param user  */ @Override public void saveUser(UserEntity user) { mongoTemplate.save(user); } /**  * 根據用戶名查詢對象  * @param userName  * @return  */ @Override public UserEntity findUserByUserName(String userName) { Query query=new Query(Criteria.where("userName").is(userName)); UserEntity user = mongoTemplate.findOne(query , UserEntity.class); return user; } /**  * 更新對象  * @param user  */ @Override public void updateUser(UserEntity user) { Query query=new Query(Criteria.where("id").is(user.getId())); Update update= new Update().set("userName", user.getUserName()).set("passWord", user.getPassWord()); //更新查詢返回結果集的第一條 mongoTemplate.updateFirst(query,update,UserEntity.class); //更新查詢返回結果集的全部 // mongoTemplate.updateMulti(query,update,UserEntity.class); } /**  * 刪除對象  * @param id  */ @Override public void deleteUserById(Long id) { Query query=new Query(Criteria.where("id").is(id)); mongoTemplate.remove(query,UserEntity.class); } }

 

五、開發對應的測試方法

@RunWith(SpringRunner.class) @SpringBootTest public class UserDaoTest { @Autowired private UserDao userDao; @Test public void testSaveUser() throws Exception { UserEntity user=new UserEntity(); user.setId(2l); user.setUserName("小明"); user.setPassWord("fffooo123"); userDao.saveUser(user); } @Test public void findUserByUserName(){ UserEntity user= userDao.findUserByUserName("小明"); System.out.println("user is "+user); } @Test public void updateUser(){ UserEntity user=new UserEntity(); user.setId(2l); user.setUserName("天空"); user.setPassWord("fffxxxx"); userDao.updateUser(user); } @Test public void deleteUserById(){ userDao.deleteUserById(1l); } }

 

六、查看驗證結果

可使用工具mongoVUE工具來鏈接後直接圖形化展現查看,也能夠登陸服務器用命令來查看springboot

1.登陸mongos服務器

bin/mongo -host localhost -port 20000app

二、切換到test庫ide

use testspring-boot

三、查詢userEntity集合數據工具

db.userEntity.find()測試

根據3查詢的結果來觀察測試用例的執行是否正確。

到此springboot對應mongodb的增刪改查功能已經所有實現。

 

多數據源mongodb的使用

在多mongodb數據源的狀況下,咱們換種更優雅的方式來實現

 

一、pom包配置

添加lombok和spring-boot-autoconfigure包引用

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-autoconfigure</artifactId> <version>RELEASE</version> </dependency>
  • Lombok - 是一個能夠經過簡單的註解形式來幫助咱們簡化消除一些必須有但顯得很臃腫的Java代碼的工具,經過使用對應的註解,能夠在編譯源碼的時候生成對應的方法。簡單試瞭如下這個工具還挺好玩的,加上註解咱們就不用手動寫 getter\setter、構建方式相似的代碼了。

  • spring-boot-autoconfigure - 就是spring boot的自動化配置

 

二、配置文件使用YAML的形式添加兩條數據源,以下:

mongodb:  primary:  host: 192.168.9.60  port: 20000  database: test  secondary:  host: 192.168.9.60  port: 20000  database: test1

 

三、配置兩個庫的數據源

封裝讀取以mongodb開頭的兩個配置文件

@Data @ConfigurationProperties(prefix = "mongodb") public class MultipleMongoProperties { private MongoProperties primary = new MongoProperties(); private MongoProperties secondary = new MongoProperties(); }

配置不一樣包路徑下使用不一樣的數據源

第一個庫的封裝

@Configuration @EnableMongoRepositories(basePackages = "com.neo.model.repository.primary", mongoTemplateRef = PrimaryMongoConfig.MONGO_TEMPLATE) public class PrimaryMongoConfig { protected static final String MONGO_TEMPLATE = "primaryMongoTemplate"; }

第二個庫的封裝

@Configuration @EnableMongoRepositories(basePackages = "com.neo.model.repository.secondary", mongoTemplateRef = SecondaryMongoConfig.MONGO_TEMPLATE) public class SecondaryMongoConfig { protected static final String MONGO_TEMPLATE = "secondaryMongoTemplate"; }

讀取對應的配置信息而且構造對應的MongoTemplate

@Configuration public class MultipleMongoConfig { @Autowired private MultipleMongoProperties mongoProperties; @Primary @Bean(name = PrimaryMongoConfig.MONGO_TEMPLATE) public MongoTemplate primaryMongoTemplate() throws Exception { return new MongoTemplate(primaryFactory(this.mongoProperties.getPrimary())); } @Bean @Qualifier(SecondaryMongoConfig.MONGO_TEMPLATE) public MongoTemplate secondaryMongoTemplate() throws Exception { return new MongoTemplate(secondaryFactory(this.mongoProperties.getSecondary())); } @Bean @Primary public MongoDbFactory primaryFactory(MongoProperties mongo) throws Exception { return new SimpleMongoDbFactory(new MongoClient(mongo.getHost(), mongo.getPort()), mongo.getDatabase()); } @Bean public MongoDbFactory secondaryFactory(MongoProperties mongo) throws Exception { return new SimpleMongoDbFactory(new MongoClient(mongo.getHost(), mongo.getPort()), mongo.getDatabase()); } }

兩個庫的配置信息已經完成。

四、建立兩個庫分別對應的對象和Repository

藉助lombok來構建對象

@Data @AllArgsConstructor @NoArgsConstructor @Document(collection = "first_mongo") public class PrimaryMongoObject { @Id private String id; private String value; @Override public String toString() { return "PrimaryMongoObject{" + "id='" + id + '\'' + ", value='" + value + '\'' + '}'; } }

對應的Repository

public interface PrimaryRepository extends MongoRepository<PrimaryMongoObject, String> { }

繼承了 MongoRepository 會默認實現不少基本的增刪改查,省了不少本身寫dao層的代碼

Secondary和上面的代碼相似就不貼出來了

 

五、最後測試

@RunWith(SpringRunner.class) @SpringBootTest public class MuliDatabaseTest { @Autowired private PrimaryRepository primaryRepository; @Autowired private SecondaryRepository secondaryRepository; @Test public void TestSave() { System.out.println("************************************************************"); System.out.println("測試開始"); System.out.println("************************************************************"); this.primaryRepository .save(new PrimaryMongoObject(null, "第一個庫的對象")); this.secondaryRepository .save(new SecondaryMongoObject(null, "第二個庫的對象")); List<PrimaryMongoObject> primaries = this.primaryRepository.findAll(); for (PrimaryMongoObject primary : primaries) { System.out.println(primary.toString()); } List<SecondaryMongoObject> secondaries = this.secondaryRepository.findAll(); for (SecondaryMongoObject secondary : secondaries) { System.out.println(secondary.toString()); } System.out.println("************************************************************"); System.out.println("測試完成"); System.out.println("************************************************************"); } }
相關文章
相關標籤/搜索