gpt4 book ai didi

java - Spring Boot JPA 按条件选择获取 NullPointerException

转载 作者:行者123 更新时间:2023-12-02 01:46:28 25 4
gpt4 key购买 nike

我是 Spring Boot 技术的新手。我正在将 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();

}

我的 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;

用户实体如下:

@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 ...

}

我的 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我无法理解这个问题。您可以在此处查看我的界面

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

钱包 Controller 中的以下行调用 UserController 中的 findUserLastLoggedIn 方法

我的钱包 Controller

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

@斯帕拉

删除 userController = new UserController 行后更新了 WalletController

enter image description here

我的代码哪里有问题,你能帮我吗?

最佳答案

当您使用nativeQuery = true时,它将在 native 运行您的查询,因此您应该以这种方式编写查询:

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

这会使您在 @Autowired 字段上出现 NullPointerException

了解更多信息请访问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);
}
}

关于java - Spring Boot JPA 按条件选择获取 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53632998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com