标签: spring-data-mongodb

How does autowiring of custom spring data (mongo) repositories configured with java config work?

I use Spring Data Mongo with repositories. In my xml-configuration everything works fine. Now I want to use Java configuration instead of xml-configuration. This is my java configuration for the repositories:

@Configuration
@EnableMongoRepositories
public class DefaultMongoDbFactoryConfig extends AbstractMongoConfiguration{

    @Value("${db.name}") private String dbName;

    @Inject
    private Mongo mongo;

    @Bean
    protected MongoDbFactory defaultMongoDbFactory() throws Exception {
        return new SimpleMongoDbFactory(mongo, dbName);
    }

    @Bean
    protected MongoTemplate defaultMongoTemplate() throws Exception {
        return new MongoTemplate(defaultMongoDbFactory());
    }

    @Override
    protected String getDatabaseName() {
        return dbName;
    }

    @Override
    public Mongo …
Run Code Online (Sandbox Code Playgroud)

java spring spring-mvc spring-data spring-data-mongodb

1
推荐指数
1
解决办法
3274
查看次数

为什么在自动装配扩展MongoRepository的接口时会出现NullPointerException?

我正在尝试编写一个使用Spring DataMongoDB获取数据的访问层类,但我有以下问题:我有以下界面:

public interface BlogDataRepository extends MongoRepository<Article, String> {
    public Article findArticleByName(String name);
}
Run Code Online (Sandbox Code Playgroud)

和访问层类:

@EnableAutoConfiguration
public class BlogDataAccessLayer {

    @Autowired
    private BlogDataRepository dataRepository;
    ...
}
Run Code Online (Sandbox Code Playgroud)

最后一个主要课程:

@EnableAutoConfiguration
public class Test implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(Test.class, args);
    }

    public void run(String... args) throws Exception {
        BlogDataAccessLayer layer = new BlogDataAccessLayer();

        Article article = new Article("test", "first article");
        layer.addArticle(article);
    }
}
Run Code Online (Sandbox Code Playgroud)

每次我试图运行应用程序,我收到了NullPointerExeption来自dataRepository位于BlogDataAccessLayer.

我不明白为什么dataRepository不自动装配.如果我搬进dataRepository …

java spring spring-data-mongodb spring-boot

1
推荐指数
1
解决办法
1953
查看次数

Spring Data Mongo:更新插入各种字段

我正在寻找使用 Spring Data 提供的 API 实现对 Mongo Collection 的upsert操作的正确方法。

详细来说,我有以下用例。集合的架构collection如下所示:

{
  _id: "some_id",
  field1: "value1",
  field2: "value2",
  subdocument1: {
    // A subdocument with some fields
  },
  subdocument2: {
    // A subdocument with some other fields
  }
}
Run Code Online (Sandbox Code Playgroud)

字段field1field2始终存在,但subdocument1subdocument2将在不同时刻插入:一个在第一次插入期间,第二个在随后的更新期间。

我看到MongoTemplate有和upsert方法。使用这种方法我必须构建自己的更新操作。

Query query = Query.query(Criteria.where("_id").is("some_id"));
Update.update("_id", "some_id")
      .set("field1", "value1")
      .set("field2", "value2")
      .set("subdocument1", subdocumentObject);
mongoTemplate.upsert(query, update, Collection.class);
Run Code Online (Sandbox Code Playgroud)

我不明白这是否是我正在寻找的以及是否有更好的方法。

java mongodb spring-data-mongodb

1
推荐指数
1
解决办法
4383
查看次数

Mongodb错误$ substrBytes:无效范围,结束索引位于UTF-8字符的中间

我正在做一个查询,从我的书集中提取属性“ titlu”的不同首字母,以便根据书籍的“ titlu”属性的首字母进行分组。我有一些以UTF-8字符开头的标题,例如Î,?,?等,但出现此错误:

在此处输入图片说明

显而易见的问题是:如何消除该错误?有两个可接受的选项:

  1. 理想情况下,我应该能够显示Î,?,?等
  2. 如果不可能的话,也可以显示I,S,T,并在I组中将以Î开头的标题归为一组,以?开头的标题也可以。在S组中,等等。

但是,转换必须在mongo查询中完成,因为我还需要计数标题。(对于解决方案2,我们需要字母I,例如,将以I开头的标题的出现与以Î开头的标题的出现进行求和)。

utf-8 mongodb aggregation-framework spring-data-mongodb

1
推荐指数
1
解决办法
813
查看次数

在Spring Data MongoDB中返回Stream时指定游标选项?

我正在使用Spring Data MongoDB(来自Spring Boot的spring-boot-starter-data-mongodb 1.5.2.RELEASE)和MongoDB 3.4.9,并定义了一个类似于以下内容的存储库:

interface MyMongoDBRepository extends CrudRepository<MyDTO, String> {
    Stream<MyDTO> findAllByCategory(String category);
}
Run Code Online (Sandbox Code Playgroud)

然后,我有一个MyService与该存储库交互的服务:

@Service
class MyService {
    @Autowired
    MyMongoDBRepository repo;

    public void doStuff() {
        repo.findAllByCategory("category")
            .map(..)
            .filter(..)
            .forEach(..)
    }
}
Run Code Online (Sandbox Code Playgroud)

数据库中有很多数据,有时会发生此错误:

2018-01-01 18:16:56.631 ERROR 1 --- [ask-scheduler-6] o.s.integration.handler.LoggingHandler : org.springframework.dao.DataAccessResourceFailureException: 
Query failed with error code -5 and error message 'Cursor 73973161000 not found on server <mongodb-server>' on server <mongodb-server>; 
nested exception is com.mongodb.MongoCursorNotFoundException: 
Query failed with error code -5 and error message …
Run Code Online (Sandbox Code Playgroud)

java spring mongodb spring-data-mongodb spring-boot

1
推荐指数
2
解决办法
2125
查看次数

Spring Data MongoDB @Transactional 失败

有人能告诉我为什么这个春季交易没有适当回滚吗?

我得到的错误是这样的:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.transaction.PlatformTransactionManager' available
Run Code Online (Sandbox Code Playgroud)

这是我的存储库,其中包含一个故意失败的保存事务:

@Repository
public class TransactionalRepository {

    private final PlayerRepository playerRepository;

    @Autowired
    public TransactionalRepository(PlayerRepository playerRepository) {
        this.playerRepository = playerRepository;
    }

    public Player saveSuccess(Player player) {
        return playerRepository.save(player);
    }

    @Transactional
    public Player saveFail(Player player) {
        player.setName("FAIL"); // should not be saved in DB if transaction rollback is successful
        player = playerRepository.save(player);
        throw new IllegalStateException("intentionally fail transaction");
    }
}
Run Code Online (Sandbox Code Playgroud)

这是测试:

@RunWith(SpringRunner.class)
@SpringBootTest
public class MongoTransactionApplicationTests {

    @Autowired
    public TransactionalRepository playerRepository;

    @Test
    public void …
Run Code Online (Sandbox Code Playgroud)

spring-transactions spring-data-mongodb mongo-java-driver

1
推荐指数
1
解决办法
4874
查看次数

带有 Spring Data JPA 的 Mongodb 文档中的 PrePersist 和 PreUpdate

我有使用问题@PrePersist,并@PreUpdate在MongoDB中我的实体有有像createAt和updateAt,一切都做工精细元场,如果它定义了一个超类@Entity,但它似乎不工作@Document。那么,什么功能,我可以使用类似的工作,@PrePersist@PreUpdate为蒙戈实体的家伙?这是我的超类

@EntityListeners(AuditingEntityListener.class)
public class ItemDocument implements Serializable {

    private static final long serialVersionUID = 5894122627332059602L;

    @Id
    private UUID id;
    @Field("created_at")
    @CreatedDate
    private long created_at;
    @Field("created_by")
    private String created_by;
    @Field("updated_at")
    @LastModifiedDate
    private long updated_at;
    @Field("updated_by")
    private String updated_by;

    @PrePersist
    protected void onPersist() {
        this.created_at = new Date().getTime();
        this.updated_at = this.created_at;
    }

    /**
     * On update.
     */
    @PreUpdate
    protected void onUpdate() {
        this.updated_at = new Date().getTime();
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的实体

@Document(collection …
Run Code Online (Sandbox Code Playgroud)

java spring mongodb spring-data spring-data-mongodb

1
推荐指数
1
解决办法
4184
查看次数

Mongo DB - 如何使用不同的名称作为键而不是属性名称

我正在使用 org.springframework.data.mongodb.core.MongoOperations 来存储 MongoDB 文档。

@Document(collection = "api_response")
public class ApiResponse {

    private String dealNumber; // deal_Number
    private String systemCode; // system_Code

}
ApiResponse response = new ApiResponse();
mongoOperations.save(response); 
Run Code Online (Sandbox Code Playgroud)

它被正确保存。我需要使用不同的键而不是实际的属性名称。而不是 dealNumber,它应该是 deal_Number 作为键。

是否可以?

spring-data spring-data-mongodb

1
推荐指数
1
解决办法
683
查看次数

@MongoId 在 Spring Data MongoDB 中通过 @Id 的用途是什么?

我正在尝试将模型添加到 Mongo Db。

我知道我可以使用 @Id 来避免在 _id 字段中创建 ObjectId。现在,在使用它时,我从org.springframework.data.mongodb.core.mapping包中遇到了 @MongoId 。

所以我的问题是我们可以在@Id 上使用@MongoId,如果是,用例是什么?不幸的是,@MongoId没有足够的可用文档

像下面这样:

import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.MongoId;

import java.util.Date;

@Document
public class LeadDetails {
    @MongoId
    private Integer id;
    private String firstName;
    private String middleName;
    private String lastName;
    private String mobile;
    private String landlineNumber;
    private Date contactedOn;
    private Date repliedOn;
    private String email;
}
Run Code Online (Sandbox Code Playgroud)

java spring mongodb spring-data spring-data-mongodb

1
推荐指数
1
解决办法
1621
查看次数

由 Docker-Compose 启动的 Mongo-Express 导致错误 [MongoError]:首次连接时无法连接到服务器 [mongo:27017]

场景:我想从同一个 docker-compose 启动 Mongo 和 Mongo-Express。

我只从 docker-compose 启动 mongodb 没有问题。当我尝试将 Mongo-Express 链接到 Mongo DB 服务时,问题就出现了。

我不确定我是否缺少 docker-compose 或 mongo-express 设置中的某些配置。我不希望这个问题成为 Mongo 设置的一部分。顺便说一句,我粘贴了整个 docker-compose 及其输出。

从波纹管日志我可以看到提高 Mongo 没有问题。当 mongo-express 尝试连接到 Mongo 服务时会出现一些问题,可能是因为我没有正确设置链接。最重要的是,我的 Spring Webflux 成功连接到具有波纹管属性的 Mongo DB。该问题实际上仅限于 mongo-express 到达 mongodb。

允许 Spring Data (spring-boot-starter-data-mongodb-reactive) 成功连接到此类 MongoDb 的 application.yml

spring:
  data:
    mongodb:
      host: 192.168.99.100
      port:  27017
      database: demodb
      authentication-database: admin
      username: root
      password: rootpassword
Run Code Online (Sandbox Code Playgroud)

docker-compose.yml

version: '3.7'

services:
  mongo-express:
    image: mongo-express
    ports:
      - 8081:8081
    environment:
      ME_CONFIG_BASICAUTH_USERNAME: admin
      ME_CONFIG_BASICAUTH_PASSWORD: q
      ME_CONFIG_MONGODB_PORT: 27017 …
Run Code Online (Sandbox Code Playgroud)

mongodb spring-data-mongodb docker docker-compose mongo-express

1
推荐指数
2
解决办法
4010
查看次数