Karthik
Karthik

Reputation: 477

Spring Boot data, MongoDB not returning results

I am reading and learning Spring Boot data with MongoDB. I have about 10 records in my database in the following format:

{
    "_id" : ObjectId("5910c7fed6df5322243c36cd"),
    name: "car"
}

Below are my Java/Spring classes:

@SpringBootApplication
public class Application {
    public static void main(String[] args) throws IOException {
        SpringApplication.run(Application.class, args);
    }
}

@Document
public class Item implements Serializable {
    private static final long serialVersionUID = -4343106526681673638L;

    @Id
    private String id;
    private String name;

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

@RepositoryRestResource(collectionResourceRel = "item", path = "items")
public interface ItemRepository<T, ID extends Serializable> extends MongoRepository<Item, String>, ItemRepositoryCustom {

}

MongoDB Configuration:

@Configuration
@EnableMongoRepositories
public class MongoConfiguration extends AbstractMongoConfiguration {

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

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

    @Override
    protected String getMappingBasePackage() {
        return "com.learning.domain";
    }
}

I have followed the docs from spring, but when I open the link in my browser:

http://localhost:1337/items

I do not get any of the items inside my database. All I get is:

{
  "_embedded" : {
    "item" : [ ]
  },
  "_links" : {
    "self" : {
      "href" : "http://localhost:1337/items"
    },
    "profile" : {
      "href" : "http://localhost:1337/profile/items"
    }
  },
  "page" : {
    "size" : 20,
    "totalElements" : 0,
    "totalPages" : 0,
    "number" : 0
  }
}

The _embedded object is empty. Do I have to explicitly create a controller and implement the methods, or does Spring-Data do it automatically? For example, I want to get the counts and I did this:

http://localhost:1337/items/count

But it gave me a 404.

Upvotes: 2

Views: 5041

Answers (1)

Karthik
Karthik

Reputation: 477

My MongoConfiguration was not being picked, so I added the details in application.properties as:

spring.data.mongodb.database=itemdb

This solved the issue and now I am getting all items from my query.

Upvotes: 4

Related Questions