空指针异常在使用Spring Boot JPA保存至数据库时发生

huangapple go评论79阅读模式
英文:

NullPointerException using Spring Boot JPA when trying to save to database

问题

以下是翻译好的内容:

@SpringBootApplication
public class DesktopAutoTradingApplication {

	public static void main(String[] args) throws JsonProcessingException {
		SpringApplication.run(DesktopAutoTradingApplication.class, args);
		MarketsBinanceController marketsBinanceController = new MarketsBinanceController();
		marketsBinanceController.saveListOfMarketsBinance();
	}
}

@Controller
public class MarketsBinanceController{

    @Autowired
    RequestServices requestService;

    public void saveListOfMarketsBinance() throws JsonProcessingException {
        String resourceURL;
        RestTemplate restTemplate = new RestTemplate();
        ObjectMapper mapper = new ObjectMapper();
        ResponseEntity<String> response;
        MarketsBinance marketsBinance;

        resourceURL = "https://api.cryptowat.ch/markets/binance";
        response = restTemplate.getForEntity(resourceURL, String.class);
        JsonNode root = mapper.readTree(response.getBody());
        JsonNode result = root.get("result");
        System.out.println(result);
        List<MarketsBinance> markets = new ArrayList<>();
        for(JsonNode item : result){
            marketsBinance = new MarketsBinance();
            MarketsBinanceDto marketsBinanceDto;
            marketsBinanceDto = mapper.treeToValue(item,MarketsBinanceDto.class);
            marketsBinance.setId(marketsBinanceDto.getId());
            marketsBinance.setExchange(marketsBinanceDto.getExchange());
            marketsBinance.setPair(marketsBinanceDto.getPair());
            marketsBinance.setActive(marketsBinanceDto.getActive());
            marketsBinance.setRoute(marketsBinanceDto.getRoute());
            markets.add(marketsBinance);
            requestService.saveMarketsBinance(markets);
        }
    }
}

@Service
@Transactional
public class RequestServices {

    @Autowired
    private MarketsBinanceDAO marketsBinanceDAO;

    public void saveMarketsBinance(List<MarketsBinance> markets){
        marketsBinanceDAO.saveAll(markets);
    }
}

@Component
public interface MarketsBinanceDAO extends CrudRepository<MarketsBinance, Long> {

}

@Entity
public class MarketsBinance {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long tableId;
    private Long id;
    private String exchange;
    private String pair;
    private Boolean active;
    private String route;

//getters and setters

public class MarketsBinanceDto {

    private Long id;
    private String exchange;
    private String pair;
    private Boolean active;
    private String route;

//getters and setters

Exception in thread "main" java.lang.NullPointerException
	at Controller.MarketsBinanceController.saveListOfMarketsBinance(MarketsBinanceController.java:46)
	at com.DAT.DesktopAutoTrading.DesktopAutoTradingApplication.main(DesktopAutoTradingApplication.java:16)

以下是程序运行时添加了第一个答案中提供的解决方案后收到的错误信息:

Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'Controller.MarketsBinanceController' available
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:352)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:343)
	at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1127)
	at com.DAT.DesktopAutoTrading.DesktopAutoTradingApplication.main(DesktopAutoTradingApplication.java:15)
2020-09-07 12:24:03.545  INFO 22756 --- [         task-1] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-09-07 12:24:03.553  INFO 22756 --- [         task-1] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
英文:

I am planning to play around with some trading data, and made a request to retrieve some markets data that I wish to store in mysql.

Since yesterday I have been stuck on a NullPointerException in my code. On StackOverflow I often see the error to be of trying to instantiate the Service for example, or forgotten annotations.

For me it seems to be going wrong whenever I try to use the Autowired Service. I invoke the method (that makes the data request in the Controller) from the main method for now. This does mean I have to instantiate in order to get there. This is probably where it goes wrong. I might be missing the concept of how to deal with this properly or how to save my data to the DAO. Hope someone can steer me in the right direction.

See the code below:

@SpringBootApplication
public class DesktopAutoTradingApplication {


	public static void main(String[] args) throws JsonProcessingException {

		SpringApplication.run(DesktopAutoTradingApplication.class, args);
		MarketsBinanceController marketsBinanceController = new MarketsBinanceController();
		marketsBinanceController.saveListOfMarketsBinance();
	}
@Controller
public class MarketsBinanceController{

    @Autowired
    RequestServices requestService;

    public void saveListOfMarketsBinance() throws JsonProcessingException {
        String resourceURL;
        RestTemplate restTemplate = new RestTemplate();
        ObjectMapper mapper = new ObjectMapper();
        ResponseEntity&lt;String&gt; response;
        MarketsBinance marketsBinance;

        resourceURL = &quot;https://api.cryptowat.ch/markets/binance&quot;;
        response = restTemplate.getForEntity(resourceURL, String.class);
        JsonNode root = mapper.readTree(response.getBody());
        JsonNode result = root.get(&quot;result&quot;);
        System.out.println(result);
        List&lt;MarketsBinance&gt; markets = new ArrayList&lt;&gt;();
        for(JsonNode item : result){
            marketsBinance = new MarketsBinance();
            MarketsBinanceDto marketsBinanceDto;
            marketsBinanceDto = mapper.treeToValue(item,MarketsBinanceDto.class);
            marketsBinance.setId(marketsBinanceDto.getId());
            marketsBinance.setExchange(marketsBinanceDto.getExchange());
            marketsBinance.setPair(marketsBinanceDto.getPair());
            marketsBinance.setActive(marketsBinanceDto.getActive());
            marketsBinance.setRoute(marketsBinanceDto.getRoute());
            markets.add(marketsBinance);
            requestService.saveMarketsBinance(markets);
        }
    }
}
@Service
@Transactional
public class RequestServices {

    @Autowired
    private MarketsBinanceDAO marketsBinanceDAO;

    public void saveMarketsBinance(List&lt;MarketsBinance&gt; markets){
        marketsBinanceDAO.saveAll(markets);
    }
}
@Component
public interface MarketsBinanceDAO extends CrudRepository&lt;MarketsBinance, Long&gt; {

}
@Entity
public class MarketsBinance {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long tableId;
    private Long id;
    private String exchange;
    private String pair;
    private Boolean active;
    private String route;

//getters and setters

public class MarketsBinanceDto {

    private Long id;
    private String exchange;
    private String pair;
    private Boolean active;
    private String route;

//getters and setters
Exception in thread &quot;main&quot; java.lang.NullPointerException
at Controller.MarketsBinanceController.saveListOfMarketsBinance(MarketsBinanceController.java:46)
at com.DAT.DesktopAutoTrading.DesktopAutoTradingApplication.main(DesktopAutoTradingApplication.java:16)

Below you find the error message received upon running the program adding the proposed solution in the first answer.

Exception in thread &quot;main&quot; org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type &#39;Controller.MarketsBinanceController&#39; available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:352)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:343)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1127)
at com.DAT.DesktopAutoTrading.DesktopAutoTradingApplication.main(DesktopAutoTradingApplication.java:15)
2020-09-07 12:24:03.545  INFO 22756 --- [         task-1] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-09-07 12:24:03.553  INFO 22756 --- [         task-1] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit &#39;default&#39;

答案1

得分: 0

你应该使用Spring创建和配置的类型为 MarketsBinanceController 的 bean,而不是 MarketsBinanceController marketsBinanceController = new MarketsBinanceController();

要在主方法中获取此 bean,你应该获取 ApplicationContext。你可以通过 SpringApplication.run(DesktopAutoTradingApplication.class, args); 的返回对象来获取 ApplicationContext

完整的代码示例:

ConfigurableApplicationContext context = SpringApplication.run(DesktopAutoTradingApplication.class, args);
MarketsBinanceController marketsBinanceController = context.getBean(MarketsBinanceController.class);
marketsBinanceController.saveListOfMarketsBinance();
英文:

You should use bean of type MarketsBinanceController that Spring created and configured instead of MarketsBinanceController marketsBinanceController = new MarketsBinanceController();.
<br>
To get this bean in main method you should get ApplicationContext. ApplicationContext you can get as returned object from SpringApplication.run(DesktopAutoTradingApplication.class, args);.
<br>
Complete code example:

ConfigurableApplicationContext context = SpringApplication.run(DesktopAutoTradingApplication.class, args);
MarketsBinanceController marketsBinanceController = context.getBean(MarketsBinanceController.class);
marketsBinanceController.saveListOfMarketsBinance();

huangapple
  • 本文由 发表于 2020年9月7日 17:08:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/63774559.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定