Rest API with Spring Data MongoDB - Repository method not working

1.5k views Asked by At

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"
}

When I open the url:

http://localhost:8090/items

I get an exhaustive list of all items. However, I want to use the methods of MongoRepository such as findById, count etc. When I use them as such:

http://localhost:8090/items/count
http://localhost:8090/items/findById/5910c7fed6df5322243c36cd
http://localhost:8090/items/findById?id=5910c7fed6df5322243c36cd

I get a 404.

My setup is as so:

@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 {

}

What am I doing wrong? Do I need to implement the methods as defined by MongoRepository or will they be automatically implemented? I am lost and have been trying to figure this out for so long. I do not have any methods in my controller, its empty.

2

There are 2 answers

1
yamenk On BEST ANSWER

You have to declare the findById method in order for it to be exposed.

Item findById(String id);
Item findByName(String name);

Note that you don't need to implement the methods. SpringBoot will analyse the method name and provide the proper implementation

0
Hema On

I had same issue,

After removing @Configuration,@ComponentScan everything worked fine.