如何在spring data mongoDB中指定数据库名

时间:2022-09-11 16:52:35

I am using Mongo repositories to perform CRUD operations as in the code below. Although this code works, but the documents and collections are created in a different DB than the one that I want. How can I explicitly specify a DB name to which documents will be stored.

我正在使用Mongo存储库执行CRUD操作,如下面的代码所示。虽然这段代码可以工作,但是文档和集合是在不同于我想要的DB中创建的。如何显式地指定要存储文档的DB名称。

The POJO class:

POJO类:

@Document(collection = "actors")
public class Actor 
{
  @Id
  private String id;
  ...
  //constructor
  //setters & getters
}

The repository:

存储库:

public interface ActorRepository extends MongoRepository<Actor, String> 
{
  public Actor findByFNameAndLName(String fName, String lName);
  public Actor findByFName (String fName);
  public Actor findByLName(String lName);
}

The service that uses the repository:

使用存储库的服务:

@Service
public class ActorService 
{
  @Autowired
  private ActorRepository actorRepository;

  public Actor insert(Actor a)
  {
    a.setId(null);
    return actorRepository.save(a);
  }
} 

And I access the service from a REST controller class:

我从REST控制器类访问服务:

@RestController
public class Controllers 
{

  private static final Logger logger = Logger.getLogger(Controllers.class);
  private static final ApplicationContext ctx = new  AnnotationConfigApplicationContext(SpringMongoConfig.class);

  @Autowire
  private ActorService actorService;

  @RequestMapping(value="/createActor", method=RequestMethod.POST)
  public @ResponseBody String createActor(@RequestParam(value = "fName") String fName,
        @RequestParam(value = "lName") String lName,
        @RequestParam(value = "role") String role)
  {
    return actorService.insert(new Actor(null,fName,lName,role)).toString();

  }

 ...
}

I have created this spring mongoDB configuration class which has the option of setting DB name, but could not figure out how to use it with the repositories above.

我创建了这个spring mongoDB配置类,它有设置DB名称的选项,但是我不知道如何在上面的存储库中使用它。

@Configuration
public class SpringMongoConfig extends AbstractMongoConfiguration
{ 
    @Bean
    public GridFsTemplate gridFsTemplate() throws Exception 
    {
        return new GridFsTemplate(mongoDbFactory(), mappingMongoConverter());
    }

    @Override
    protected String getDatabaseName() 
    {
        return "MyDB";
    }

    @Override
    @Bean
    public Mongo mongo() throws Exception 
    {
        return new MongoClient("localhost" , 27017 );
    }

    public @Bean MongoTemplate mongoTemplate() throws Exception 
    {
        return new MongoTemplate(mongo(), getDatabaseName());
    }    
}

3 个解决方案

#1


15  

Add to the application.properties a line : spring.data.mongodb.database=yourdb

添加到应用程序。属性行:spring.data.mongodb.database=yourdb

That worked for me, maybe too late for you but this could help someone looking for the same problem. see more properties here!

这对我有用,也许对你来说太晚了,但这可以帮助寻找同样问题的人。看到更多的属性!

#2


2  

FWIW, I am able to change the mongo database name using the combination of Sezin Karli and Sam's code above, despite the solution not working in Sam's situation.

FWIW,我可以使用Sezin Karli和上面Sam的代码更改mongo数据库名,尽管解决方案在Sam的情况下不起作用。

My POM file contains only this reference to mongodb:

我的POM文件只包含对mongodb的引用:

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

Specifically, first I created a beans.xml file in resources with the following information:

具体地说,首先我创建了一个bean。xml文件在资源中有以下信息:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mongo="http://www.springframework.org/schema/data/mongo"
       xsi:schemaLocation="http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <mongo:mongo-client credentials="user:password@database" />

    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongo" ref="mongo"/>
        <constructor-arg name="databaseName" value="myDBName"/>
    </bean>
</beans>

Next, I changed my main to load the configuration via:

接下来,我改变了主要的配置,通过:

ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

Note: This must execute first in main().

注意:这必须首先在main()中执行。

Lastly, I added extends AbstractMongoConfiguration to my start-class and implemented

最后,我将AbstractMongoConfiguration扩展到我的start类并实现

    @Override
    public String getDatabaseName() {
        return "myDBName";
    }

    @Override
    @Bean
    public Mongo mongo() throws Exception {
        return new MongoClient("localhost" , 27017 );
    }

The database name was specified in two locations. Unfortunately, this appears necessary for success.

数据库名称在两个位置中指定。不幸的是,这似乎是成功的必要条件。

#3


1  

Your configuration seems to be fine Sam. Are you sure there's a db called "MyDB"? Or are you sure that you don't also set the db name in somewhere else (such as app context xml) like below.

你的配置看起来不错,萨姆。你确定有一个db叫MyDB吗?或者,您确定您没有在其他地方(如应用程序上下文xml)设置db名称,如下面所示。

 <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
     <constructor-arg name="mongo" ref="mongo"/>
     <constructor-arg name="databaseName" value="demo"/>
   </bean>

#1


15  

Add to the application.properties a line : spring.data.mongodb.database=yourdb

添加到应用程序。属性行:spring.data.mongodb.database=yourdb

That worked for me, maybe too late for you but this could help someone looking for the same problem. see more properties here!

这对我有用,也许对你来说太晚了,但这可以帮助寻找同样问题的人。看到更多的属性!

#2


2  

FWIW, I am able to change the mongo database name using the combination of Sezin Karli and Sam's code above, despite the solution not working in Sam's situation.

FWIW,我可以使用Sezin Karli和上面Sam的代码更改mongo数据库名,尽管解决方案在Sam的情况下不起作用。

My POM file contains only this reference to mongodb:

我的POM文件只包含对mongodb的引用:

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

Specifically, first I created a beans.xml file in resources with the following information:

具体地说,首先我创建了一个bean。xml文件在资源中有以下信息:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mongo="http://www.springframework.org/schema/data/mongo"
       xsi:schemaLocation="http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <mongo:mongo-client credentials="user:password@database" />

    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongo" ref="mongo"/>
        <constructor-arg name="databaseName" value="myDBName"/>
    </bean>
</beans>

Next, I changed my main to load the configuration via:

接下来,我改变了主要的配置,通过:

ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

Note: This must execute first in main().

注意:这必须首先在main()中执行。

Lastly, I added extends AbstractMongoConfiguration to my start-class and implemented

最后,我将AbstractMongoConfiguration扩展到我的start类并实现

    @Override
    public String getDatabaseName() {
        return "myDBName";
    }

    @Override
    @Bean
    public Mongo mongo() throws Exception {
        return new MongoClient("localhost" , 27017 );
    }

The database name was specified in two locations. Unfortunately, this appears necessary for success.

数据库名称在两个位置中指定。不幸的是,这似乎是成功的必要条件。

#3


1  

Your configuration seems to be fine Sam. Are you sure there's a db called "MyDB"? Or are you sure that you don't also set the db name in somewhere else (such as app context xml) like below.

你的配置看起来不错,萨姆。你确定有一个db叫MyDB吗?或者,您确定您没有在其他地方(如应用程序上下文xml)设置db名称,如下面所示。

 <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
     <constructor-arg name="mongo" ref="mongo"/>
     <constructor-arg name="databaseName" value="demo"/>
   </bean>