简体   繁体   English

Spring Boot JPA按条件选择以获取NullPointerException

[英]Spring Boot JPA Select by criteria getting NullPointerException

I am new at Spring Boot Technology.I am using JPA Repository with MySQL DB.I am getting an error as NullPointer Exception. 我是Spring Boot Technology的新手,正在将JPA Repository与MySQL DB一起使用,并由于NullPointer Exception而收到错误消息。

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


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

}

My Table 我的桌子

   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 as like this: 用户实体如下所示:

@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 : 我的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]

my repository is here I couldn't understand the problem.You can see the my interface here 我的存储库在这里,我无法理解问题。您可以在此处看到我的界面

My UserController class 我的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();

the below line in Wallet Controller calls the method findUserLastLoggedIn in UserController Wallet Controller中的以下行在UserController中调用方法findUserLastLoggedIn

My 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 @Spara

Updated WalletController after deleting userController = new UserController line 删除userController =新的UserController行后,更新了WalletController

enter image description here 在此处输入图片说明

Where is the problem on my code, could you pleaase help me? 我的代码上的问题在哪里,您能帮我个忙吗?

Instead of native query you can use spring data jpa itself like below. 您可以使用spring数据jpa本身来代替本地查询,如下所示。

public List<User> findByIsUserLoggedIn(Integer isUserLoggedIn);

If boolean field then try with below. 如果是布尔字段,请尝试以下内容。

public Iterable<Entity> findByIsUserLoggedInTrue();

The JPA repository section query creation has the following methods. JPA存储库部分查询创建具有以下方法。

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

So you can use 所以你可以使用

@Query
public Iterable<Entity> findByEnabledTrue();

When you use nativeQuery = true it will run your query natively so you should write query in this way: 当您使用nativeQuery = true ,它将在本地运行查询,因此您应该以这种方式编写查询:

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

The other way is to do not use nativeQuery : 另一种方法是不使用nativeQuery

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

Please delete this line in your WalletController: 请在您的WalletController中删除此行:

userController = new UserController();

This makes you NullPointerException on @Autowired fields 这使您在@Autowired字段上出现NullPointerException

For more information please visit here 欲了解更多信息,请访问这里

@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);
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM