The repository is not injected.
In LoginController either create a constructor with your repositories (preferable way) or mark fields as @Autowired.
The repository is not injected.
In LoginController either create a constructor with your repositories (preferable way) or mark fields as @Autowired.
Check your LoginController class.
You have @Autowired only in StudentRepo, but the other 2 repos don't have such annotation. They won't be autowired and will be set as null by default.
Place @Autowired annotation there also, and check again.
Spring Boot Test cannot give a clear message but throw NPE now when @SpringBootConfiguration cannot be found
Spring: NullPointerException trying to access findAll() @Repository
rest - Spring Boot - Null Pointer Exception - Stack Overflow
java - Spring Boot Unit test gives error: Cannot invoke "" because "this.taskService" is null - Stack Overflow
Spring Boot NullPointerException
How do I fix NullPointerException in Spring Boot?
NullPointerException Spring service
java.lang.NullPointerException: Cannot invoke "com.example.demo.student.StudentRepository.findAll()" because "this.studentRepository" is null
I do have a @Repository annotated above my StudentRepository class. I also used @Autorwired above the constructor in my StudentService class. I think the problem is with dependency injection but I don't see why.
Related code:
//StudentRepository.java
package com.example.demo.student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface StudentRepository extends JpaRepository<Student, Long> {
}
//StudentService.java
package com.example.demo.student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.time.Month;
import java.util.List;
@Service
public class StudentService {
private final StudentRepository studentRepository;
@Autowired
public StudentService(StudentRepository studentRepository) {
this.studentRepository = studentRepository;
}
public List<Student> getStudents() {
return studentRepository.findAll();
}
}
//StudentController.java
package com.example.demo.student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping(path = "api/v1/student")
public class StudentController {
private final StudentService studentService;
@Autowired
public StudentController(StudentService studentService) {
this.studentService = studentService;
}
@GetMapping
public List<Student> getStudents(StudentService studentService) {
return studentService.getStudents();
}
}which version of spring boot do you use? If you're using old version of spring, then you need to create the constructor and add @Autowired above the constructor instead of using lombok annotation. Or you can change the lombok annotations like @AllArgsConstructor(onConstructor_ = @Autowired). Or just remove the lombok annoation and add @Autowired above userService.
Also make sure userService is a Spring Bean, check the annotation in UserService, it should have @Service or @Component or if it's created by @Bean method.
make sure you have an implementation of UserService marked as @Service. if you have it, then save all files and re-run the application.
I think your problem is related with the lack of a @Component annotation in your BoardDao class.
The component should have a @Component annotation to instantiate the singleton to be injected in your Service Layer.
@Component
public class BoardDao extends SqlSessionDaoSupport{
@Autowired
SqlSessionTemplate session;
public List<BoardDto> listboard(BoardDto dto) {
System.out.println("dao.");
List<BoardDto> result = session.selectList("boarddate.listboard", dto);
return result;
}
}
If the problem persist, you may try with the @Repository annotation. Sadly I haven't used the class SqlSessionDaoSupport, so I don't know exactly the best annotation for that.
In my case it was with a Map, I wanted to increase its value, but this initial one will not exist, therefore it is null.
map.put(0, map.get(0) 1);
It was fixed by adding a validation, like so:
map.put(0, map.get(0) != null ? map.get(0) + 1 : 1);
The solution for it was to add this dependency into maven
<dependency>
<groupId>org.spockframework</groupId>
<artifactId>spock-spring</artifactId>
<version>1.3-groovy-2.5</version>
<scope>test</scope>
</dependency>
It was not enough to add just the spock-core.
Your test class is missing the annotation @RunWith(SpringRunner.class)
@SpringBootTest
@RunWith(SpringRunner.class)
class EpisodeServiceTest extends Specification {
I'm pretty new at Java and was trying to do a CRUD, the process was going pretty smoothly until i had to make the create function to the table with a composite key.
At first i thought the problem was with the Dependecy Injection, but it's working just fine in the methods getByStateAndModelId() and getAll().I also tried to set the names for the EquipmentModel and EquipmentState in the createEmshe (In the POST i just insert the Id of both State and Models, and the Value, so the names from Model and State coming from the DTO are null and i thought that maybe that was the cause). But then, both the equipmentModelRepository and the equipmentStateRepository returned the NullPointerException too, what i'm missing?here's the relevant code:
The service:
package com.api.forestoperation.emshe;
import java.util.List;
import java.util.UUID;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.api.forestoperation.equipmentmodel.EquipmentModelModel;
import com.api.forestoperation.equipmentmodel.EquipmentModelRepository;
import com.api.forestoperation.equipmentstate.EquipmentStateModel;
import com.api.forestoperation.equipmentstate.EquipmentStateRepository;
@Service
public class EquipmentModelStateHourlyEarningsService {
@Autowired
EquipmentModelStateHourlyEarningsRepository emsheRepository;
@Autowired
EquipmentModelRepository equipmentModelRepository;
@Autowired
EquipmentStateRepository equipmentStateRepository;
public List<EquipmentModelStateHourlyEarningsModel> getAllEmshe() {
return emsheRepository.findAll();
}
public EquipmentModelStateHourlyEarningsModel createEmshe(EquipmentModelStateHourlyEarningsDTO emsheDTO) {
var emsheModel = new EquipmentModelStateHourlyEarningsModel();
BeanUtils.copyProperties(emsheDTO, emsheModel);
EquipmentModelModel emsheModelInfo = emsheModel.getId().getEquipmentModel();
EquipmentStateModel emsheStateInfo = emsheModel.getId().getEquipmentState();
EquipmentModelStateHourlyEarningsPK emshePk = new EquipmentModelStateHourlyEarningsPK(emsheModelInfo,
emsheStateInfo);
emsheModel.setId(emshePk);
return emsheRepository.save(emsheModel);
}
public EquipmentModelStateHourlyEarningsModel getEmsheByStateAndModelId(UUID modelId, UUID stateId) {
var modelExists = equipmentModelRepository.findById(modelId).orElse(null);
var stateExists = equipmentStateRepository.findById(stateId).orElse(null);
if (modelExists != null && stateExists != null) {
EquipmentModelStateHourlyEarningsPK emshePk = new EquipmentModelStateHourlyEarningsPK(modelExists,
stateExists);
EquipmentModelStateHourlyEarningsModel emsheModel = emsheRepository.findById(emshePk).orElse(null);
return emsheModel;
}
return null;
}
}The Controller:
package com.api.forestoperation.emshe;
import java.util.List;
import java.util.UUID;
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.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class EquipmentModelStateHourlyEarningsController {
@Autowired
EquipmentModelStateHourlyEarningsService emsheService;
@PostMapping("/equipment-model-state-hourly-earnings")
public ResponseEntity<Object> saveEmshe(@RequestBody EquipmentModelStateHourlyEarningsDTO emsheDTO) {
var savedEmshe = new EquipmentModelStateHourlyEarningsService().createEmshe(emsheDTO);
return savedEmshe != null
? ResponseEntity.status(HttpStatus.CREATED)
.body("EquipmentModelStateHourlyEarnings created with Sucess")
: ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
}
@GetMapping("/equipment-model-state-hourly-earnings")
public ResponseEntity<List<EquipmentModelStateHourlyEarningsModel>> getAllEmshe() {
List<EquipmentModelStateHourlyEarningsModel> equipments = emsheService.getAllEmshe();
return ResponseEntity.status(HttpStatus.OK).body(equipments);
}
@GetMapping("/equipment-model-state-hourly-earnings/{modelId}/{stateId}")
public ResponseEntity<Object> getEmsheByModelAndStateId(@PathVariable(value = "modelId") UUID modelId,
@PathVariable(value = "stateId") UUID stateId, EquipmentModelStateHourlyEarningsPK emshePk) {
EquipmentModelStateHourlyEarningsModel emsheModel = emsheService.getEmsheByStateAndModelId(modelId, stateId);
return emsheModel == null ? ResponseEntity.status(HttpStatus.BAD_REQUEST).body("EMSHE nulo")
: ResponseEntity.status(HttpStatus.OK).body(emsheModel);
}
}The Repository:
package com.api.forestoperation.equipment;
import java.util.UUID;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface EquipmentRepository extends JpaRepository<EquipmentModel, UUID> {
}The Model:
package com.api.forestoperation.emshe;
import java.io.Serializable;
import com.api.forestoperation.equipmentmodel.EquipmentModelModel;
import com.api.forestoperation.equipmentstate.EquipmentStateModel;
import jakarta.persistence.Column;
import jakarta.persistence.EmbeddedId;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
@Entity
@Table(name="equipment_model_state_hourly_earnings", schema="operation")
public class EquipmentModelStateHourlyEarningsModel implements Serializable {
@EmbeddedId
private EquipmentModelStateHourlyEarningsPK id;
private static final long serialVersionUID = 1L;
@Column(name="value")
private double value;
public EquipmentModelStateHourlyEarningsPK getId() {
return id;
}
public void setId(EquipmentModelStateHourlyEarningsPK id) {
this.id = id;
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
public EquipmentModelModel getEquipmentModel() {
return id.getEquipmentModel();
}
public EquipmentStateModel getEquipmentState() {
return id.getEquipmentState();
}
}The Pk:
package com.api.forestoperation.emshe;
import java.io.Serializable;
import java.util.Objects;
import com.api.forestoperation.equipmentmodel.EquipmentModelModel;
import com.api.forestoperation.equipmentstate.EquipmentStateModel;
import jakarta.persistence.Embeddable;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
@Embeddable
public class EquipmentModelStateHourlyEarningsPK implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@ManyToOne
@JoinColumn(name = "equipment_model_id")
private EquipmentModelModel equipmentModel;
@ManyToOne
@JoinColumn(name = "equipment_state_id")
private EquipmentStateModel equipmentState;
public EquipmentModelStateHourlyEarningsPK() {
}
public EquipmentModelStateHourlyEarningsPK(EquipmentModelModel equipmentModelModel,
EquipmentStateModel equipmentStateModel) {
this.equipmentModel = equipmentModelModel;
this.equipmentState = equipmentStateModel;
}
@Override
public int hashCode() {
return Objects.hash(equipmentModel, equipmentState);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
EquipmentModelStateHourlyEarningsPK other = (EquipmentModelStateHourlyEarningsPK) obj;
return Objects.equals(equipmentModel, other.equipmentModel)
&& Objects.equals(equipmentState, other.equipmentState);
}
public EquipmentModelModel getEquipmentModel() {
return equipmentModel;
}
public void setEquipmentModel(EquipmentModelModel equipmentModel) {
this.equipmentModel = equipmentModel;
}
public EquipmentStateModel getEquipmentState() {
return equipmentState;
}
public void setEquipmentState(EquipmentStateModel equipmentState) {
this.equipmentState = equipmentState;
}
}Here's the error i get:
java.lang.NullPointerException: Cannot invoke "com.api.forestoperation.emshe.EquipmentModelStateHourlyEarningsRepository.save(Object)" because "this.emsheRepository" is null at com.api.forestoperation.emshe.EquipmentModelStateHourlyEarningsService.createEmshe(EquipmentModelStateHourlyEarningsService.java:39) ~[classes/:na] at com.api.forestoperation.emshe.EquipmentModelStateHourlyEarningsController.saveEmshe(EquipmentModelStateHourlyEarningsController.java:22) ~[classes/:na] at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103) ~[na:na] at java.base/java.lang.reflect.Method.invoke(Method.java:580) ~[na:na] at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-6.0.13.jar:6.0.13] at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150) ~[spring-web-6.0.13.jar:6.0.13] at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:118) ~[spring-webmvc-6.0.13.jar:6.0.13] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:884) ~[spring-webmvc-6.0.13.jar:6.0.13] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) ~[spring-webmvc-6.0.13.jar:6.0.13] at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-6.0.13.jar:6.0.13] at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1081) ~[spring-webmvc-6.0.13.jar:6.0.13] at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:974) ~[spring-webmvc-6.0.13.jar:6.0.13] at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1011) ~[spring-webmvc-6.0.13.jar:6.0.13] at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:914) ~[spring-webmvc-6.0.13.jar:6.0.13] at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:590) ~[tomcat-embed-core-10.1.15.jar:6.0] at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:885) ~[spring-webmvc-6.0.13.jar:6.0.13] at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:658) ~[tomcat-embed-core-10.1.15.jar:6.0] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:205) ~[tomcat-embed-core-10.1.15.jar:10.1.15] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) ~[tomcat-embed-core-10.1.15.jar:10.1.15] at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51) ~[tomcat-embed-websocket-10.1.15.jar:10.1.15] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) ~[tomcat-embed-core-10.1.15.jar:10.1.15] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) ~[tomcat-embed-core-10.1.15.jar:10.1.15] at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-6.0.13.jar:6.0.13] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.0.13.jar:6.0.13] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) ~[tomcat-embed-core-10.1.15.jar:10.1.15] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) ~[tomcat-embed-core-10.1.15.jar:10.1.15] at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-6.0.13.jar:6.0.13] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.0.13.jar:6.0.13] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) ~[tomcat-embed-core-10.1.15.jar:10.1.15] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) ~[tomcat-embed-core-10.1.15.jar:10.1.15] at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-6.0.13.jar:6.0.13] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.0.13.jar:6.0.13] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) ~[tomcat-embed-core-10.1.15.jar:10.1.15] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) ~[tomcat-embed-core-10.1.15.jar:10.1.15] at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:167) ~[tomcat-embed-core-10.1.15.jar:10.1.15] at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:90) ~[tomcat-embed-core-10.1.15.jar:10.1.15] at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:482) ~[tomcat-embed-core-10.1.15.jar:10.1.15] at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:115) ~[tomcat-embed-core-10.1.15.jar:10.1.15] at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:93) ~[tomcat-embed-core-10.1.15.jar:10.1.15] at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) ~[tomcat-embed-core-10.1.15.jar:10.1.15] at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:340) ~[tomcat-embed-core-10.1.15.jar:10.1.15] at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:391) ~[tomcat-embed-core-10.1.15.jar:10.1.15] at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63) ~[tomcat-embed-core-10.1.15.jar:10.1.15] at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:896) ~[tomcat-embed-core-10.1.15.jar:10.1.15] at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1744) ~[tomcat-embed-core-10.1.15.jar:10.1.15] at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52) ~[tomcat-embed-core-10.1.15.jar:10.1.15] at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) ~[tomcat-embed-core-10.1.15.jar:10.1.15] at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) ~[tomcat-embed-core-10.1.15.jar:10.1.15] at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-10.1.15.jar:10.1.15] at java.base/java.lang.Thread.run(Thread.java:1583) ~[na:na]
The solution is simple. You mocked a class customerDataRepository but did not instruct it the mock what to do if the corresponding method is called. Mockito mocks then default back on doing nothing by method call and if there is a return value return null.
Since your returned customerData is null you get your NPE when calling on this object. In your case this is in the error case that you get by calling getCustomerId().
To solve this issue simply instruct your mock
@Test
void removeCustomerDataWhenConsentIsNotGiven() {
CustomerData customerDataTest = customerData;
//when
Mockito.when(customerDataRepository.findCustomerByDialogId(Mockito.any())).thenReturn(new CustomerData()); // <-- Add this line
customerDataService.giveConsent(false,22L);
//then
verify(customerDataRepository,times(1)).save(customerDataTest);
}
you can obviously replace Mockito.any() with Mockito.anyInt() or 42 and new CustomerData() with a object you previously created. I think you get the idea ;)
Assuming that you have just corrected method names before posting it to Stackoverflow, and method you are calling in the test: giveConsent is, actually, the same method as methodTotest of the CustomerDataService.
Before calling customerDataService.giveConsent(false,22L);, you need to configure you repository to return some test (not null! or mocked) customerData entity:
when(customerDataRepository.findCustomerByDialogId(22L)).thenReturn(customerDataTest);
customerDataService.giveConsent(false,22L);
Note: since you are passing false as 1st variable, you will get to this branch of code
if (!consent) {
customerDataRepository.deleteById(customer.getCustomerId());
}
And in the test you are expecting save() method to be called, so the test will fail.