1、pom包配置
pom包里面添加spring-boot-starter-data-mongodb包引用
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
</dependencies>
2啃炸、在application.properties中添加配置
spring.data.mongodb.uri=mongodb://name:pass@localhost:27017/test
多個(gè)IP集群可以采用以下配置:
spring.data.mongodb.uri=mongodb://user:pwd@ip1:port1,ip2:port2/database
2矫户、創(chuàng)建數(shù)據(jù)實(shí)體
public class UserEntity implements Serializable {
private static final long serialVersionUID = -3258839839160856613L;
private Long id;
private String userName;
private String passWord;
//getter微驶、setter省略
}
3腮鞍、創(chuàng)建實(shí)體dao的增刪改查操作
dao層實(shí)現(xiàn)了UserEntity對(duì)象的增刪改查
@Component
public class UserDaoImpl implements UserDao {
@Autowired
private MongoTemplate mongoTemplate;
/**
* 創(chuàng)建對(duì)象
* @param user
*/
@Override
public void saveUser(UserEntity user) {
mongoTemplate.save(user);
}
/**
* 根據(jù)用戶名查詢對(duì)象
* @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;
}
/**
* 更新對(duì)象
* @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());
//更新查詢返回結(jié)果集的第一條
mongoTemplate.updateFirst(query,update,UserEntity.class);
//更新查詢返回結(jié)果集的所有
// mongoTemplate.updateMulti(query,update,UserEntity.class);
}
/**
* 刪除對(duì)象
* @param id
*/
@Override
public void deleteUserById(Long id) {
Query query=new Query(Criteria.where("id").is(id));
mongoTemplate.remove(query,UserEntity.class);
}
}
4弛房、開發(fā)對(duì)應(yīng)的測(cè)試方法
@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);
}
}
5道盏、查看驗(yàn)證結(jié)果
可以使用工具mongoVUE工具來連接后直接圖形化展示查看,也可以登錄服務(wù)器用命令來查看
1.登錄mongos
bin/mongo -host localhost -port 20000
2文捶、切換到test庫
use test
3荷逞、查詢userEntity集合數(shù)據(jù)
db.userEntity.find()
根據(jù)3查詢的結(jié)果來觀察測(cè)試用例的執(zhí)行是否正確。
到此springboot對(duì)應(yīng)mongodb的增刪改查功能已經(jīng)全部實(shí)現(xiàn)粹排。
多數(shù)據(jù)源mongodb的使用
在多mongodb數(shù)據(jù)源的情況下种远,我們換種更優(yōu)雅的方式來實(shí)現(xiàn)
1、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 - 是一個(gè)可以通過簡單的注解形式來幫助我們簡化消除一些必須有但顯得很臃腫的Java代碼的工具顽耳,通過使用對(duì)應(yīng)的注解坠敷,可以在編譯源碼的時(shí)候生成對(duì)應(yīng)的方法妙同。簡單試了以下這個(gè)工具還挺好玩的,加上注解我們就不用手動(dòng)寫 getter\setter常拓、構(gòu)建方式類似的代碼了渐溶。
spring-boot-autoconfigure - 就是spring boot的自動(dòng)化配置
2、配置文件使用YAML的形式添加兩條數(shù)據(jù)源弄抬,如下:
mongodb:
primary:
host: 192.168.9.60
port: 20000
database: test
secondary:
host: 192.168.9.60
port: 20000
database: test1
3茎辐、配置兩個(gè)庫的數(shù)據(jù)源
封裝讀取以mongodb開頭的兩個(gè)配置文件
@Data
@ConfigurationProperties(prefix = "mongodb")
public class MultipleMongoProperties {
private MongoProperties primary = new MongoProperties();
private MongoProperties secondary = new MongoProperties();
}
配置不同包路徑下使用不同的數(shù)據(jù)源
第一個(gè)庫的封裝
@Configuration
@EnableMongoRepositories(basePackages = "com.neo.model.repository.primary",
mongoTemplateRef = PrimaryMongoConfig.MONGO_TEMPLATE)
public class PrimaryMongoConfig {
protected static final String MONGO_TEMPLATE = "primaryMongoTemplate";
}
第二個(gè)庫的封裝
@Configuration
@EnableMongoRepositories(basePackages = "com.neo.model.repository.secondary",
mongoTemplateRef = SecondaryMongoConfig.MONGO_TEMPLATE)
public class SecondaryMongoConfig {
protected static final String MONGO_TEMPLATE = "secondaryMongoTemplate";
}
讀取對(duì)應(yīng)的配置信息并且構(gòu)造對(duì)應(yīng)的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());
}
}
兩個(gè)庫的配置信息已經(jīng)完成。
4、創(chuàng)建兩個(gè)庫分別對(duì)應(yīng)的對(duì)象和Repository
借助lombok來構(gòu)建對(duì)象
@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 + '\''
+ '}';
}
}
對(duì)應(yīng)的Repository
public interface PrimaryRepository extends MongoRepository<PrimaryMongoObject, String> {
}
繼承了 MongoRepository 會(huì)默認(rèn)實(shí)現(xiàn)很多基本的增刪改查汁汗,省了很多自己寫dao層的代碼
Secondary和上面的代碼類似就不貼出來了
5锡搜、最后測(cè)試
@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("測(cè)試開始");
System.out.println("************************************************************");
this.primaryRepository
.save(new PrimaryMongoObject(null, "第一個(gè)庫的對(duì)象"));
this.secondaryRepository
.save(new SecondaryMongoObject(null, "第二個(gè)庫的對(duì)象"));
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("測(cè)試完成");
System.out.println("************************************************************");
}
}