hibernate,repository.save-java.lang.nullpointerexception:null-对象存在时

idfiyjo8  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(336)

我写这段代码只是为了简单地将新数据保存到mysql db,创建了类、存储库和主控制器,它实际上只适用于一个类,但不适用于这个类,请欣赏一些指针,因为我不太明白为什么会使用空指针:
代码:主控制器:

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

eclipse控制台的输出错误:下面的检查显示对象是从Map中提取的:-创建exchange构造函数-创建的exchange构造函数,orange-exhange name is,orange-exchange[ideexchange=0,e\u name=orange]
2018-05-21 15:59:43.528错误5118---[nio-8080-exec-4]o.a.c.c.[/].[dispatcherservlet]:路径为[]的上下文中servlet[dispatcherservlet]的servlet.service()引发异常[请求处理失败;嵌套异常是java.lang.nullpointerexception],其根本原因是
java.lang.nullpointerexception:com.instantmoney.moneyservices.maincontroller.addnewexchange(maincontroller)处为空。java:47)~[类/:na]
exchange存储库:

public interface ExchangeRepository extends CrudRepository<Exchange, Long> {

}
交换班

@Entity 
public class Exchange {

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

private String e_name;

public Exchange() {}

//接受者和接受者
curl

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

j91ykkif1#

试试这个

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

相关问题