I am working on a Junit5 integration testing with spring-test-mongo. While executing the below code, I am facing invalid method reference error.
import com.jupiter.tools.spring.test.mongo.annotation.MongoDataSet;
import com.jupiter.tools.spring.test.mongo.junit5.meta.annotation.MongoDbIntegrationTest;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
#MongoDbIntegrationTest
public class JUnit5ExampleTest {
#Autowired
private MongoTemplate mongoTemplate;
#Test
#MongoDataSet(value = "/dataset/bar_dataset.json")
void testPopulatingByMongoDataSet() throws Exception {
Bar simpleDoc = mongoTemplate.findById("55f3ed00b1375a48e618300b", Bar.class);
Assertions.assertThat(simpleDoc)
.isNotNull()
.extracting(Bar::getId, Bar::getData);
}
}
Bar.class
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document
#AllArgsConstructor
#NoArgsConstructor
#Data
public class Bar {
#Id
private String id;
private String data;
}
build.gradle:
plugins {
id 'java'
}
group 'org.example'
version '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.projectlombok:lombok:1.18.20'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0'
testImplementation 'com.jupiter-tools:spring-test-mongo:0.15'
testImplementation 'org.springframework.boot:spring-boot-starter-data-mongodb:2.5.4'
testImplementation 'org.springframework.boot:spring-boot-starter-test:2.5.4'
testImplementation 'org.projectlombok:lombok:1.16.20'
}
test {
useJUnitPlatform()
}
Related
I'm trying to make a crud app using SpringBoot + JPA + HIBERNATE + GRADLE + MYSQL. My issue is that when I hit an #PostMapping endpoint to save a user, an empty object get's saved in database. Only id is generated but the other column shows null. Also when I hit #GetMapping it returns empty object list . I'm using PostMan for requests.
Images of Postamn Requests
create
all
Mysql Database
build.gradle
plugins {
id 'java'
id 'org.springframework.boot' version '3.0.1'
id 'io.spring.dependency-management' version '1.1.0'
}
group = 'db.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '19'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'com.mysql:mysql-connector-j'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('test') {
useJUnitPlatform()
}
application.properties
spring.jpa.hibernate.ddl-auto=update
spring.jpa.generate-ddl=true
spring.datasource.url=jdbc:mysql://localhost:3306/auto?autoReconnect=true&useSSL=false&createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mainApplication.java
package db.example.autodbconnect;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class AutodbconnectApplication {
public static void main(String[] args) {
SpringApplication.run(AutodbconnectApplication.class, args);
}
}
UserEntity
package db.example.autodbconnect.entities;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
#Entity
#Table
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column
private String name;
}
User JPA Repository
package db.example.autodbconnect.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import db.example.autodbconnect.entities.User;
#Repository
public interface UserRepository extends JpaRepository<User,Long> {
}
User Service
package db.example.autodbconnect.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import db.example.autodbconnect.entities.User;
import db.example.autodbconnect.repositories.UserRepository;
#Service
public class UserService {
#Autowired
private UserRepository userRepo;
public User create(User body) {
return userRepo.save(body);
}
public List<User> findAll(){
List<User> res=userRepo.findAll();
return res;
}
}
User Controller
package db.example.autodbconnect.contoller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import db.example.autodbconnect.entities.User;
import db.example.autodbconnect.service.UserService;
#RestController
#RequestMapping("/users")
public class UserController {
#Autowired
private UserService userService;
#PostMapping("/create")
public ResponseEntity<User> create(#RequestBody User body) {
return new ResponseEntity<User>(userService.create(body), HttpStatus.CREATED);
}
#GetMapping("/all")
public ResponseEntity<List<User>> findALL(){
return new ResponseEntity<List<User>>(userService.findAll(),HttpStatus.OK);
}
}
You have not added getter setter methods for each field that's why it is storing null values
solution-
1-either add getter setter method for each field or
2-you can also add lombook dependency and use #Data annotation it will add getter setter method for you
Hope it will help you
I come to you as a last hope, I'm a newbie in programming and I'm having a trouble starting my project using Spring and Gradle. I'm getting an error every time I try to launch my project and I don't understand why...
Here is the error
o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-08-10 00:08:24.364 INFO 16456 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.64]
2022-08-10 00:08:24.383 INFO 16456 --- [ restartedMain] o.a.c.c.C.[Tomcat-8].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-08-10 00:08:24.383 INFO 16456 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 221 ms
2022-08-10 00:08:24.388 WARN 16456 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.TechTicketing.repository.UserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
2022-08-10 00:08:24.388 INFO 16456 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2022-08-10 00:08:24.393 INFO 16456 --- [ restartedMain] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-08-10 00:08:24.395 ERROR 16456 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field userRepository in com.example.TechTicketing.service.UserService required a bean of type 'com.example.TechTicketing.repository.UserRepository' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.example.TechTicketing.repository.UserRepository' in your configuration.
I searched a lot about this error, but every solutions I found doesn't seem to work, I checked my package disposition it looks fine :
Package Dispostion
I did use the annotations #Service, #RestController, #Entity, #Repository in my classes, I did try to remove the #Autowired, the application starts, but as soon as I do a get request it gives a null pointer so it's basically the same issue... I tried modifying the options in the configuration of my main class but either it doesn't change anything, either it crashes... I tried all the options I found online but I was unable to fix the issue. Here are some of my code.
UserEntity
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
#Entity
#Data
#Table(name="User")
public class UserEntity {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private long IdUser;
private String Name;
private String FirstName;
private String Mail;
private String Password;
private String Phone;
private String Address;
private String TechCode;
private int Role;
#JsonIgnore
#OneToMany(mappedBy="IdInternalInter")
private List<InterventionEntity> intervention;
#JsonIgnore
#ManyToOne
#JoinColumn(name="IdRole")
private RoleEntity role;
}
UserRepository
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.example.TechTicketing.entity.UserEntity;
#Repository
public interface UserRepository extends CrudRepository<UserEntity, Long>{
}
UserController
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.example.TechTicketing.entity.UserEntity;
import com.example.TechTicketing.service.UserService;
#RestController
public class UserController {
#Autowired
private UserService userService;
#GetMapping("/user/{id}")
public UserEntity getUserById(#PathVariable("id")final Long id) {
Optional<UserEntity> user = userService.getUserById(id);
if(user.isPresent()) {
return user.get();
} else {
return null;
}
}
#GetMapping("/users")
public Iterable<UserEntity> getUsers(){
return userService.getUsers();
}
#PostMapping("/addUser")
public UserEntity addUser(#RequestBody UserEntity user) {
return userService.addUser(user);
}
#PutMapping("/updateUser")
public UserEntity updateUser(#RequestBody UserEntity user) {
return userService.updateUser(user);
}
}
UserService
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.TechTicketing.entity.UserEntity;
import com.example.TechTicketing.repository.UserRepository;
import lombok.Data;
#Service
#Data
public class UserService {
#Autowired
private UserRepository userRepository;
public Optional<UserEntity> getUserById(final Long userID){
return userRepository.findById(userID);
}
public Iterable<UserEntity> getUsers(){
return userRepository.findAll();
}
public UserEntity addUser(UserEntity user) {
UserEntity addedUser = userRepository.save(user);
return addedUser;
}
public UserEntity updateUser(UserEntity user){
UserEntity existingUser = userRepository.findById(user.getIdUser()).orElse(null);
existingUser.setAddress(user.getAddress());
existingUser.setFirstName(user.getFirstName());
existingUser.setIntervention(user.getIntervention());
existingUser.setMail(user.getMail());
existingUser.setName(user.getName());
existingUser.setPassword(user.getPassword());
existingUser.setPhone(user.getPhone());
existingUser.setRole(user.getRole());
existingUser.setTechCode(user.getTechCode());
return userRepository.save(existingUser);
}
}
TechTicketingApp
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.context.annotation.Configuration;
//#ComponentScan("com.example.TechTicketing.repository")
#Configuration
#EnableAutoConfiguration(
exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
#SpringBootApplication
public class TechTicketingApplication {
public static void main(String[] args) {
SpringApplication.run(TechTicketingApplication.class, args);
}
}
build.gradle
id 'org.springframework.boot' version '2.7.1'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
id 'war'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'com.microsoft.sqlserver:mssql-jdbc'
annotationProcessor 'org.projectlombok:lombok'
providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('test') {
useJUnitPlatform()
}
Please tell me if you need more, I can also eventually provide a link to a github folder if needed ! thanks in advance !
looks like UserRepository is not annotate with #Repository if not spring data
if spring data try to add below
#EnableJpaRepositories("com.example.TechTicketing.repository") #EntityScan(basePackages="com.example.TechTicketing.entity")
I have been experimenting with spring boot since a while now, and I have noticed few strange things. Sometimes we have to include #ComponentScan in main class to solve the error which goes like try defining the bean of type package.name .
For eg. I created many sprint boot application without including #ComponentScan or any such annotation like #EnableJpaRepositories but recently I created one spring boot project which says Cannot find bean of type RepositoryName and when I used #ComponentScan , It worked. Why is that ?
You can see the code below:
Spring Class:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#ComponentScan(basePackages = {"com.example.demo.repository"})
#SpringBootApplication
public class SampleApplication {
public static void main(String[] args) {
SpringApplication.run(SampleApplication.class, args);
}
}
Entity Class:
package com.example.demo.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.data.annotation.Id;
import lombok.Data;
#Entity(name = "admin")
#Data
public class Admin {
#Id
#GenericGenerator(name = "admin_id_seq" , strategy = "increment")
#GeneratedValue(generator="admin_id_seq",strategy = GenerationType.AUTO)
private Long id;
private String username;
private String password;
private String name;
}
Controller
package com.example.demo.controller;
import com.example.demo.dto.AdminRegisterDTO;
import com.example.demo.repository.AdminRepository;
import com.example.demo.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class AdminController {
#Autowired
private AdminService adminService;
#PostMapping("/login")
public AdminRegisterDTO registerAdmin(#RequestBody AdminRegisterDTO adminRegisterDTO){
return adminService.registerAdmin(adminRegisterDTO);
}
}
Service class
package com.example.demo.service.impl;
import com.example.demo.dto.AdminRegisterDTO;
import com.example.demo.entity.Admin;
import com.example.demo.repository.AdminRepository;
import com.example.demo.service.AdminService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class AdminServiceImpl implements AdminService {
#Autowired
private AdminRepository adminRepository;
#Override
public AdminRegisterDTO registerAdmin(AdminRegisterDTO adminRegisterDTO) {
Admin admin = new Admin();
BeanUtils.copyProperties(adminRegisterDTO,admin);
Admin savedAdmin = adminRepository.save(admin);
AdminRegisterDTO adminRegisterDTO1 = new AdminRegisterDTO();
BeanUtils.copyProperties(savedAdmin,adminRegisterDTO1);
return adminRegisterDTO1;
}
}
Repository:
package com.example.demo.repository;
import com.example.demo.entity.Admin;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface AdminRepository extends JpaRepository<Admin, Long> {
}
If I remove #ComponentScan I get the following error message:
***************************
APPLICATION FAILED TO START
***************************
Description:
Field adminRepository in com.example.demo.service.impl.AdminServiceImpl required a bean of type 'com.example.demo.repository.AdminRepository' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.example.demo.repository.AdminRepository' in your configuration.
I am aware that there are a lot of questions related to the same but none of them worked for some reason. Hence, posting the same and hoping to get some response.
I am trying to follow the SpingBoot application tutorial from Youtube and build the same application. But for some reason I get following error:
***************************
APPLICATION FAILED TO START
***************************
Description:
Field postRepository in com.testingconverter.service.PostService required a bean of type 'com.testingconverter.repository.PostRepository' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.testingconverter.repository.PostRepository' in your configuration.
Following are my classes:
Main SpringBootApplication class:
package com.testingconverter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class})
public class TestingConverterApplication {
public static void main(String[] args) {
SpringApplication.run(TestingConverterApplication.class, args);
}
}
Controller class:
package com.testingconverter.controller;
import com.testingconverter.entities.PostEntity;
import com.testingconverter.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
#RestController
public class BlogController {
#Autowired
private PostService postService;
#GetMapping(value = "/")
public String index() {
return "index";
}
#GetMapping(value = "/posts")
public List<PostEntity> posts() {
return postService.getAllPost();
}
#PostMapping(value = "/posts")
public void publishPost(#RequestBody PostEntity post) {
postService.insert(post);
}
}
My Entity class:
package com.testingconverter.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.util.Date;
#Entity
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
#ToString
public class PostEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String title;
private String body;
private Date date;
}
My Repository class:
package com.testingconverter.repository;
import com.testingconverter.entities.PostEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface PostRepository extends JpaRepository<PostEntity, Long> {
}
My Service class:
package com.testingconverter.service;
import com.testingconverter.entities.PostEntity;
import com.testingconverter.repository.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public class PostService {
#Autowired
private PostRepository postRepository;
public List<PostEntity> getAllPost() {
return postRepository.findAll();
}
public void insert(PostEntity post) {
postRepository.save(post);
}
}
I tried many things like adding the #ComponentScan etc but nothing seems to work for me. Can someone please explain to me what's going wrong here? How can I fix this?
Following is my project structure:
You excluding default database configuration. Remove that exclude part and add your database configuration in application properties files.
If you going to exclude then you have to create you datasource in configuration file.
#Bean
public DataSource getDataSource() {
DataSourceBuilder dataSourceBuilder =
DataSourceBuilder.create();
dataSourceBuilder.driverClassName("");
dataSourceBuilder.url("");
dataSourceBuilder.username("");
dataSourceBuilder.password("");
return dataSourceBuilder.build();
}
I am new to spring, trying to create a spring project with mongodb. I get the following error when I run it.
2018-05-23 22:15:20.077 WARN 11610 --- [main]
ConfigServletWebServerApplicationContext : Exception encountered during
context initialization - cancelling refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error
creating bean with name 'voteController': Unsatisfied dependency
expressed through field 'voteSvc'; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException: Error
creating bean with name 'voteService': Unsatisfied dependency expressed
through field 'voteRepo'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name 'votesRepository': Invocation of init method failed;
nested exception is
org.springframework.data.mapping.PropertyReferenceException: No
property findAll found for type Vote!
2018-05-23 22:15:20.081 INFO 11610 --- [main]
o.apache.catalina.core.StandardService : Stopping service [Tomcat]
Here my Application.java file
package com.hello;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
#SpringBootApplication
#ComponentScan("com.hello")
public class Application implements CommandLineRunner {
#Autowired
private UserRepository userRepo;
private IdeaRepository ideaRepo;
private VotesRepository voteRepo;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Override
public void run(String... args) throws Exception {
}
}
Here is my VoteController.java
package com.hello;
import java.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.*;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.boot.autoconfigure.*;
#Controller
#RequestMapping("/api")
public class VoteController{
#Autowired
IVoteService voteSvc;
#RequestMapping(value = "/votes", method = RequestMethod.GET)
public List<Vote> findByIdeaId(int ideaId)
{
List<Vote> votes = voteSvc.GetVotesByIdeaId(ideaId);
return votes;
}
#RequestMapping(value = "/votes", method = RequestMethod.POST)
public Vote PostByIdeaId(Vote vote)
{
Vote votes = voteSvc.SaveVotesByIdeaId(vote);
return votes;
}
#RequestMapping(value = "/votes", method = RequestMethod.DELETE)
public void DeleteByIdeaId(Vote vote)
{
voteSvc.DeleteVotesByIdeaId(vote);
}
}
Here is VoteService.java
package com.hello;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.*;
import java.util.List;
import java.util.*;
#Service
public class VoteService implements IVoteService {
#Autowired
VotesRepository voteRepo;
public List<Vote> GetVotesByIdeaId(int ideaId)
{
List<Vote> votes = voteRepo.FindAll(ideaId);
//List<Vote> votes = new ArrayList<Vote>();
return votes;
}
public Vote SaveVotesByIdeaId(Vote vote)
{
Vote voteIdea = voteRepo.save(vote);
return voteIdea;
}
public void DeleteVotesByIdeaId(Vote vote)
{
voteRepo.delete(vote);
}
}
Here is my VoteRepository.java
package com.hello;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.*;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
#Repository
public interface VotesRepository extends MongoRepository<Vote, String> {
public List<Vote> FindAll(int IdeaId);
}
Here is my Interface
package com.hello;
import java.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.*;
#Service
public interface IVoteService {
public List<Vote> GetVotesByIdeaId(int ideaId);
public Vote SaveVotesByIdeaId(Vote vote);
public void DeleteVotesByIdeaId(Vote vote);
}
Here is my gradle.build file
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:2.0.1.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
bootJar {
baseName = 'idea-platform'
version = '0.1.0'
}
jar {
manifest {
attributes(
'Main-Class': 'hello.Application'
)
}
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
compile("org.springframework.boot:spring-boot-devtools")
compile("org.springframework.boot:spring-boot-starter-data-mongodb")
testCompile("junit:junit")
}
Here is my entity
package com.hello;
import org.springframework.data.annotation.Id;
public class Vote {
#Id
public String id;
public String user;
public Integer ideaId;
public Vote() {}
}
I looked into other similar questions, none of them helped me to resolve.
The method you define on your repository doesn't match the Spring Data Repositories approach. Supposing ideaId is a property on Vote, a method to find all Vote's with the given ideaId should be something like this:
#Repository
public interface VotesRepository extends MongoRepository<Vote, String> {
public List<Vote> findByIdeaId(int ideaId);
}
Have a look here for more details on how to implement Spring Data Repositories.
P.S.: On a side note, try adhering to the Java naming convention to start your method and parameter names with a lowercase.
This is not the full solution, but I noticed this issue too. Each of your repositories probably need to be autowired, not just the first one.
You had:
#Autowired
private UserRepository userRepo;
private IdeaRepository ideaRepo;
private VotesRepository voteRepo;
But I think you wanted:
#Autowired
private UserRepository userRepo;
#Autowired
private IdeaRepository ideaRepo;
#Autowired
private VotesRepository voteRepo;