I'm trying to use Spring Data JPA to make a timed-quizz app. It gets the questions from the database when the socket opens and sends the data to the client after that . I've implemented the websocket and and my repositories. Yet, I'm getting a nullpointerexception whenever I try to access the data inside the database from the WebSocket Class . I've even autowired my data but yet nothing works. Here is the code of the websocket :
@Component
@ServerEndpoint("/websocket/{tentativeId}")
// This annotation is equivalent to setting access URLs
public class WebSocket {
private Session session;
@Autowired
TentativeRepository tentativeRepository;
@Autowired
QuestionRepository questionRepository;
private static CopyOnWriteArraySet<WebSocket> webSockets =new CopyOnWriteArraySet<>();
private static Map<String,Session> sessionPool = new HashMap<String,Session>();
@OnOpen
public void onOpen(Session session, @PathParam(value="tentativeId")String tentativeId) {
this.session = session;
webSockets.add(this);
sessionPool.put(tentativeId, session);
Long c = questionRepository.count();// ERRRORRRR HEREEEE
Question q = questionRepository.findById1(Long.parseLong(tentativeId));
this.sendOneMessage("1", c.toString());
I'm literally getting an error of null pointer on the questionRepository.count() even though it's autowired. Can someone give me an idea on what's happening exactly. When I try to use that Repository on a Controller. it works fine.
Here is the error : It's on the line of Long c = questionRepository.count()
java.lang.NullPointerException: null
at com.neoexams.app.websocket.WebSocket.onOpen(WebSocket.java:44) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]