Spring Boot中如何使用MongoDB呢?

乔欣 SpringBoot 发布时间:2023-02-13 17:11:02 阅读数:13538 1
下文笔者讲述Springboot中使用MongoDB的方法及示例分享,如下所示

MongoDB简介

MongoDB:
   是一个高性能,开源,无模式的文档型数据库
   是当前NoSql数据库中比较热门的一种数据库
   是基于分布式文件存储的数据库,由C++语言开发

MongoDB:
   集合中没有列、行和关系概念
   它适用于大量无固定格式的数据存储
   如:日志,JSON数据的缓存
   不适用于复杂的多文档级联查询
下文笔者将讲述SpringBoot对MongoDB的操作方法分享,如下所示
SpringBoot操作MongoDB的实现思路:
    1.引入相应的starter  spring-boot-starter-data-mongodb
	2.设置相应的application.properties
	3.创建数据库实体
	4.编写Dao层操作数据库
例:MongoDB增删改查的示例分享
 
 pom包配置
   引入spring-boot-starter-data-mongodb

如:

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


//application.properties中添加配置
//单数据库下配置信息
spring.data.mongodb.uri=mongodb://name:pass@localhost:27017/test
//多个IP集群可以采用以下配置
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对象的增删改查

@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(18);
        user.setUserName("猫猫");
        user.setPassWord("java265.com");
        userDao.saveUser(user);
    }

    @Test
    public void findUserByUserName(){
       UserEntity user= userDao.findUserByUserName("猫猫");
       System.out.println("用户信息是:"+user);
    }

    @Test
    public void updateUser(){
        UserEntity user=new UserEntity();
        user.setId(16);
        user.setUserName("晓晓");
        user.setPassWord("pwdtest");
        userDao.updateUser(user);
    }

    @Test
    public void deleteUserById(){
        userDao.deleteUserById(88);
    }

}

多数据源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>

//application.properties设置
mongodb:
  primary:
    host: 192.168.8.91
    port: 20000
    database: test
  secondary:
    host: 192.168.8.92
    port: 20000
    database: test1

//配置两个库的数据源

@Data
@ConfigurationProperties(prefix = "mongodb")
public class MultipleMongoProperties {

    private MongoProperties primary = new MongoProperties();
    private MongoProperties secondary = new MongoProperties();
}

//第一个库的封装
@Configuration
@EnableMongoRepositories(basePackages = "com.java265.model.repository.primary",
        mongoTemplateRef = PrimaryMongoConfig.MONGO_TEMPLATE)
public class PrimaryMongoConfig {

    protected static final String MONGO_TEMPLATE = "primaryMongoTemplate";
}

//第二个库的封装
@Configuration
@EnableMongoRepositories(basePackages = "com.java265.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

@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
//会默认实现很多基本的增删改查 

//测试 
@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("************************************************************");
    }

}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaFramework/SpringBoot/202302/5779.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者