Spring Boot JPA Выберите по критериям, получая исключение NullPointerException - PullRequest
0 голосов
/ 05 декабря 2018

Я новичок в Spring Boot Technology. Я использую репозиторий JPA с MySQL DB. Я получаю ошибку как исключение NullPointer.

@Repository
@Transactional
public interface UserRepository extends JpaRepository<User, Integer> {   


    @Query(value="SELECT * FROM User u WHERE u.isUserLoggedIn = 1", nativeQuery = true)
    List<User> findUserLastLoggedIn();

}

Моя таблица

   CREATE TABLE `user` (  `id` int(11) NOT NULL AUTO_INCREMENT,
  `_id` varchar(30) DEFAULT NULL,
  `email` varchar(40) NOT NULL,
  `password` varchar(300) NOT NULL,
  `salt` varchar(100) DEFAULT NULL,
  `status` int(11) NOT NULL DEFAULT (1),
  `insert_date` datetime DEFAULT (now()),
  `last_login_time` datetime DEFAULT (now()),
  `name` varchar(100) DEFAULT NULL,
  `surname` varchar(100) DEFAULT NULL,
  `alias_name` varchar(100) DEFAULT NULL,
  `access_token` varchar(100) DEFAULT NULL,
  `refresh_token` varchar(100) DEFAULT NULL,
  `is_user_logged_in` tinyint(1) NOT NULL,
  PRIMARY KEY (`id`)
   ) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4 
     COLLATE=utf8mb4_0900_ai_ci;

User Entity как это:

@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)

private int id;

private String _id;
private String email;
private String password;
private String salt;
private int status;
private Date insertDate;
private Date lastLoginTime;
private String name;
private String surname;
private String aliasName;
private String accessToken;
private String refreshToken;
private int isUserLoggedIn;

//getter and setter ...

}

My StackTrace:

java.lang.NullPointerException: null
at me.sikke.UserController.findUserLastLoggedIn(UserController.java:111) ~[classes/:na]
at me.sikke.WalletController.createWallet(WalletController.java:25) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_191]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_191]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_191]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:877) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:783) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:866) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.31.jar:8.5.31]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.31.jar:8.5.31]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496) [tomcat-embed-core-8.5.31.jar:8.5.31]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.31.jar:8.5.31]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.31.jar:8.5.31]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.31.jar:8.5.31]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.31.jar:8.5.31]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) [tomcat-embed-core-8.5.31.jar:8.5.31]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.31.jar:8.5.31]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790) [tomcat-embed-core-8.5.31.jar:8.5.31]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1468) [tomcat-embed-core-8.5.31.jar:8.5.31]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.31.jar:8.5.31]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_191]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_191]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.31.jar:8.5.31]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_191]

мой репозиторийздесь Я не мог понять проблему. Вы можете увидеть мой интерфейс здесь

Мой класс UserController

@RestController
public class UserController {

@Autowired
UserRepository sikkeRespository;

@RequestMapping(value = "/getAccessToken", method = RequestMethod.POST)
public ResponseEntity<String> getAccessToken(@RequestBody LoginUser loginUser) {
    List<User> userList = sikkeRespository.findUserLastLoggedIn();
    if (userList != null && userList.size() > 0) {
        return new ResponseEntity<String>("There are currently active users. 
  Please exit and try again.", HttpStatus.OK);
    }
    if (SikkeHelper.checkLoginUser(loginUser)) {
        String username = loginUser.getEmail();
        String password = loginUser.getPassword();
        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(new BasicNameValuePair("grant_type", "password"));
        urlParameters.add(new BasicNameValuePair("username", username));
        urlParameters.add(new BasicNameValuePair("password", password));
        try {
            String jsonString = ConnectionInfo.call(SikkeConstant.accessTokenUrl, urlParameters);
            User user = new User();
            if (jsonString != null) {
                JSONObject jsonObj = new JSONObject(jsonString);
                String status = jsonObj.getString("status");
                if (SikkeConstant.STATUS_SUCCESS.equals(status)) {
                    System.out.println("Login Succeed : " + 
    jsonObj.getString("email"));
                    user.setPassword(password);
                    SikkeHelper.fillUserFromJson(jsonObj, user);
                    User userExisting = 
sikkeRespository.findByEmail(username);
                    userExisting.setIsUserLoggedIn(1);
                    if (userExisting != null) {
                        userExisting.setAccessToken(user.getAccessToken());

 userExisting.setRefreshToken(user.getRefreshToken());
                        sikkeRespository.save(userExisting);
                    } else {
                        sikkeRespository.save(user);
                    }
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
            throw new SikkeException(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            throw new SikkeException(e.getMessage());
        }
    }
    return new ResponseEntity<String>("Session successfully opened.", 
   HttpStatus.OK);
    }

@RequestMapping(value = "/registerUser", method = RequestMethod.POST)
public ResponseEntity<String> registerUser(@RequestBody LoginUser loginUser) 
{
    if (SikkeHelper.checkLoginUser(loginUser)) {
        String username = loginUser.getEmail();
        String password = loginUser.getPassword();
        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(new BasicNameValuePair("email", username));
        urlParameters.add(new BasicNameValuePair("password", password));
        urlParameters.add(new BasicNameValuePair("password_confirm", 
  password));
        try {
            String jsonString = 
  ConnectionInfo.call(SikkeConstant.registerUserUrl, urlParameters);
            User user = new User();
            if (jsonString != null) {
                JSONObject jsonObj;

                jsonObj = new JSONObject(jsonString);
                String status = jsonObj.getString("status");
                if (SikkeConstant.STATUS_SUCCESS.equals(status)) {
                    JSONObject userJson = jsonObj.getJSONObject("user");
                    user.setPassword(password);
                    SikkeHelper.fillUserFromJson(userJson, user);
                    sikkeRespository.save(user);
                } else if (SikkeConstant.STATUS_ERROR.equals(status)) {
                    System.out.println(jsonObj.getString("message"));
                }
            }
        } catch (JSONException e) {
            System.out.println(e.getMessage());
            throw new SikkeException(e.getMessage());
        } catch (IOException e) {
            throw new SikkeException(e.getMessage());
        }
    }
    return new ResponseEntity<String>("User created.", HttpStatus.OK);
   }

@RequestMapping(value = "/logOut", method = RequestMethod.GET)
public ResponseEntity<String> logOut() {
    int effectedRow = sikkeRespository.logoutAllUser();
    return new ResponseEntity<String>("Logout done successfully.", 
HttpStatus.OK);
}

public List<User> findUserLastLoggedIn() {
    List<User> userList = sikkeRespository.findUserLastLoggedIn();
    return userList;
  }
 }


List<User> userList = userController.findUserLastLoggedIn();

строка ниже в Wallet Controllerвызывает метод findUserLastLoggedIn в UserController

Мой WalletController

@RestController
 public class WalletController {

@Autowired
WalletRepository walletRepository;
@Autowired
UserController userController;

@RequestMapping(value = "/createWallet")
public ResponseEntity<String> createWallet() {
    Wallet wallet = new Wallet();
    userController = new UserController();
    List<User> userList = userController.findUserLastLoggedIn();
    if (userList == null) {
        return new ResponseEntity<>("Active user not found. You must login 
 to the system.", HttpStatus.OK);
    }
    if (userList.size() == 1) {
        User user = null;//userList.get(0);
        wallet.setwOwnerId(Integer.parseInt(user.get_id()));
        WalletKey walletKey = WalletKey.getWalletKeys();
        wallet.setwPubKey(walletKey.getPublicKey());
        wallet.setwZeugma(walletKey.getPrivateKey());
        wallet.setwNumber(walletKey.getWalletNumber());
        walletRepository.save(wallet);
        return new ResponseEntity<>("Wallet created.", HttpStatus.OK);
    }
    return new ResponseEntity<String>("Wallet creation failed", 
 HttpStatus.OK);
}
}

@ Spara

Обновленный WalletController после удаления userController = новая строка UserController

введите описание изображения здесь

Где проблема в моем коде, не могли бы вы мне помочь?

Ответы [ 2 ]

0 голосов
/ 05 декабря 2018

Когда вы используете nativeQuery = true, он будет выполнять ваш запрос изначально, поэтому вы должны написать запрос следующим образом:

@Query(value="SELECT * FROM User u WHERE u.is_user_logged_in = 1", nativeQuery = true)
List<User> findUserLastLoggedIn();

Другой способ - не использовать nativeQuery:

@Query(value="SELECT u FROM User u WHERE u.isUserLoggedIn = 1")
List<User> findUserLastLoggedIn();

Пожалуйста, удалите эту строку в вашем WalletController:

userController = new UserController();

Это сделает вас NullPointerException в @Autowired полях

Для получения дополнительной информации, пожалуйста, посетите здесь

@RestController
 public class WalletController {

@Autowired
WalletRepository walletRepository;
@Autowired
UserRepository userRepository;

@RequestMapping(value = "/createWallet")
public ResponseEntity<String> createWallet() {
    Wallet wallet = new Wallet();
    List<User> userList = userRepository.findUserLastLoggedIn();
    if (userList == null) {
        return new ResponseEntity<>("Active user not found. You must login 
 to the system.", HttpStatus.OK);
    }
    if (userList.size() == 1) {
        User user = null;//userList.get(0);
        wallet.setwOwnerId(Integer.parseInt(user.get_id()));
        WalletKey walletKey = WalletKey.getWalletKeys();
        wallet.setwPubKey(walletKey.getPublicKey());
        wallet.setwZeugma(walletKey.getPrivateKey());
        wallet.setwNumber(walletKey.getWalletNumber());
        walletRepository.save(wallet);
        return new ResponseEntity<>("Wallet created.", HttpStatus.OK);
    }
    return new ResponseEntity<String>("Wallet creation failed", 
 HttpStatus.OK);
}
}
0 голосов
/ 05 декабря 2018

Вместо нативного запроса вы можете использовать саму пружинную информацию jpa, как показано ниже.

public List<User> findByIsUserLoggedIn(Integer isUserLoggedIn);

Если поле логическое, тогда попробуйте следующее.

public Iterable<Entity> findByIsUserLoggedInTrue();

Раздел репозитория JPA создание запроса имеет следующие методы.

True    findByActiveTrue()  … where x.active = true
False   findByActiveFalse() … where x.active = false

Таким образом, вы можете использовать

@Query
public Iterable<Entity> findByEnabledTrue();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...