gpt4 book ai didi

java - Hibernate,repository.save - java.lang.NullPointerException : null - while Object exist

转载 作者:行者123 更新时间:2023-11-29 17:33:54 25 4
gpt4 key购买 nike

我编写这段代码只是为了将新数据保存到 mySql 数据库,创建类、存储库和主 Controller ,它实际上适用于一个类,但不适用于这个类,感谢一些指针,因为我真的不明白为什么空指针:

Code: main controller:

    @GetMapping(path = "/addExchange") 
public @ResponseBody String addNewExchange (@RequestParam String exchange)
{
//check1
System.out.println("creating Exchange constructor");
Exchange e = new Exchange();
//check 2
System.out.println("created exchange constructor, " + exchange);
e.setE_name(exchange);
//check 3
System.out.println("Exhange name is, " + e.getE_name());
//check 4
System.out.println(e);
exchangeRepository.save(e);
return "Saved Exchange";
}

Output error from Eclipse Console: my checks below show object is picked up from the mapping: - creating Exchange constructor - created exchange constructor, orange - Exhange name is, orange - Exchange [idexchange=0, e_name=orange]

2018-05-21 15:59:43.528 错误 5118 --- [nio-8080-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet] : servlet [dispatcherServlet] 的 Servlet.service()在路径 [] 的上下文中抛出异常 [请求处理失败;嵌套异常是 java.lang.NullPointerException] 其根本原因

java.lang.NullPointerException: null 在 com.instantmoney.MoneyServices.MainController.addNewExchange(MainController.java:47) ~[classes/:na]

Exchange Repository:

public interface ExchangeRepository extends CrudRepository<Exchange, Long> {

}

Exchange class

    @Entity 
public class Exchange {

@Id
@GeneratedValue (strategy = GenerationType.AUTO)
private int idexchange;

private String e_name;

public Exchange() {}

//getter 和 setter

Curl

http://localhost:8080/moneyservice/addExchange?exchange=orange

最佳答案

试试这个

@Controller
public class ExchangeController {

@RequestMapping(path = "/addExchange", method = RequestMethod.POST)
public @ResponseBody String addNewExchange (@RequestParam String exchange)
{
if (exchange != null ) {
Exchange e = new Exchange();
e.setE_name(exchange);
exchangeRepository.save(e);
return "Saved Exchange";
} else {
return new BadRequestException("exchange name can not be null!");
}
}

@Autowired
public ExchangeController(ExchangeRepository exchangeRepository) {
this.exchangeRepository = exchangeRepository;
}

private ExchangeRepository exchangeRepository;
}

关于java - Hibernate,repository.save - java.lang.NullPointerException : null - while Object exist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50444648/

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