【问题标题】:spring JPA to post in API requestspring JPA 在 API 请求中发布
【发布时间】:2025-11-29 01:35:01
【问题描述】:

我在这里尝试使用 findby 函数从 mysql db 中逐行获取数据,它工作正常,但下一步我尝试访问 API 以通过 http @987654321 将所需数据从我的表填充到 API @ 并将 processDate 更改为当前日期,但是当我尝试实现 commandlineruner 时出现错误

错误:

java.lang.IllegalStateException:无法执行 CommandLineRunner, 引起:java.lang.IllegalMonitorStateException: null

API 格式如下:

{
  "ChannelID":"113", # static string no change on it
  "MSISDN":"XXX", # i have to fill it wil my msisdn 
  "ServiceID":"XXX" i have to fill it with my param1
}

AccessingDataJpaApplication 类:

@SpringBootApplication
public class AccessingDataJpaApplication implements CommandLineRunner {

    private static final Logger logger = LoggerFactory.getLogger(AccessingDataJpaApplication.class);
    @Autowired

    private Bulk_repositoryRepository bulk_repositoryRepository;

    public static void main(String[] args) {
        SpringApplication.run(AccessingDataJpaApplication.class);
    }
    Date currentDate = new Date();

    @Override
    public void run(String... args) throws Exception {
         RestTemplate restTemplate = new RestTemplate();
         HttpHeaders headers = new HttpHeaders();
         headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
         headers.setBasicAuth("######", "#####");

         while(true) {

            for (Bulk_repository churnss : bulk_repositoryRepository.findAllByStatusAndCampTypeAndCampStartDateLessThanAndCampEndDateGreaterThanEqual(0,54,currentDate,currentDate)) {
                logger.info(churnss.toString());
                AddOfferRequest AddOffer = new AddOfferRequest("113", churnss.getMsisdn(),churnss.getParam1());

                logger.info(AddOffer.toString());
                HttpEntity<AddOfferRequest> entity = new HttpEntity<AddOfferRequest>(AddOffer,headers);

                ResponseEntity<String> responseEntity = restTemplate.exchange(
                "API LINK.......", HttpMethod.POST, entity, String.class);

                if(responseEntity.getStatusCode() == HttpStatus.OK){
                    String response = responseEntity.getBody();
                    logger.info(response);

                    churnss.setStatus(1);
                    churnss.setProcessDate(new Date());
                    logger.info(churnss.toString());
                    bulk_repositoryRepository.save(churnss);
                }
            }
            wait(1000);
        }
    }
}

AddOfferRequest 类:

public class AddOfferRequest {

    private String ChannelID="113";
    private String MSISDN;
    private String ServiceID;

    public AddOfferRequest() {
    }
    public AddOfferRequest(String channelID,String mSISDN,String serviceID ) {
        this.MSISDN = mSISDN;
        this.ServiceID = serviceID;

    }

    public void setMSISDN(String mSISDN) {
        this.MSISDN = mSISDN;
    }

    public void setServiceID(String serviceID) {
        this.ServiceID = serviceID;
    }

    public String getChannelID() {
        return ChannelID;
    }

    public String getMSISDN() {
        return MSISDN;
    }

    public String getServiceID() {
        return ServiceID;
    }

}

Bulk_repository 类:

@Entity
@Table(name = "BULK_REPOSITORY")
public class Bulk_repository {

   @Id
   @GeneratedValue(strategy=GenerationType.AUTO)
   @Column(name = "id")
   private long id;

   @Column(name = "msisdn")
   private String msisdn;

   @Column(name = "camp_start_date")   
   private Date campStartDate;

   @Column(name = "camp_end_date")
   private Date campEndDate;

   @Column(name = "camp_type")
   private int campType;

   @Column(name = "camp_cd")
   private String camp_cd;

   @Column(name = "status")
   private int status;

   @Column(name = "process_date")
   private Date processDate;

   @Column(name = "entry_date")
   private Date entryDate;

   @Column(name = "entry_user")
   private String entry_user;

   @Column(name = "param1")
   private String param1;

   @Column(name = "param2")
   private String param2;

   @Column(name = "param3")
   private String param3;

   @Column(name = "param4")
   private String param4;

   @Column(name = "param5")
   private String param5;

   @Column(name = "error_desc")
   private String error_desc;

   @Column(name = "fulfilment_status")
   private int fulfilment_status;
## then getter and setters and to tostring

Bulk_repositoryRepository 类:

public interface Bulk_repositoryRepository extends CrudRepository<Bulk_repository, Long> {
      List<Bulk_repository>findAllByStatusAndCampTypeAndCampStartDateLessThanAndCampEndDateGreaterThanEqual(int status, int campType,Date currentDate, Date currentDate1);

      Bulk_repository findById(long id);
}

堆栈跟踪:

2019-10-26 17:25:47.563  INFO 10275 --- [           main] c.e.a.AccessingDataJpaApplication        : Starting AccessingDataJpaApplication on ubuntu with PID 10275 (/home/devops/Documents/workspace-spring-tool-suite-4-4.4.0.RELEASE/gs-accessing-data-jpa-complete/target/classes started by devops in /home/devops/Documents/workspace-spring-tool-suite-4-4.4.0.RELEASE/gs-accessing-data-jpa-complete)
2019-10-26 17:25:47.572  INFO 10275 --- [           main] c.e.a.AccessingDataJpaApplication        : No active profile set, falling back to default profiles: default
2019-10-26 17:25:50.970  INFO 10275 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-10-26 17:25:51.141  INFO 10275 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 149ms. Found 1 repository interfaces.
2019-10-26 17:25:51.948  INFO 10275 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$58bd9157] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-10-26 17:25:52.578  INFO 10275 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-10-26 17:25:52.693  INFO 10275 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-10-26 17:25:52.711  INFO 10275 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.22]
2019-10-26 17:25:53.002  INFO 10275 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-10-26 17:25:53.003  INFO 10275 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 5219 ms
2019-10-26 17:25:53.389  INFO 10275 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2019-10-26 17:25:53.790  INFO 10275 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2019-10-26 17:25:53.891  INFO 10275 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2019-10-26 17:25:54.339  INFO 10275 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.3.10.Final}
2019-10-26 17:25:54.342  INFO 10275 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2019-10-26 17:25:54.755  INFO 10275 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2019-10-26 17:25:55.225  INFO 10275 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2019-10-26 17:25:56.861  INFO 10275 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-10-26 17:25:54.214  INFO 10275 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-10-26 17:25:54.299  WARN 10275 --- [           main] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2019-10-26 17:25:54.798  INFO 10275 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-10-26 17:25:54.804  INFO 10275 --- [           main] c.e.a.AccessingDataJpaApplication        : Started AccessingDataJpaApplication in 9.283 seconds (JVM running for 16.131)
2019-10-26 17:25:54.908  INFO 10275 --- [           main] o.h.h.i.QueryTranslatorFactoryInitiator  : HHH000397: Using ASTQueryTranslatorFactory
2019-10-26 17:25:55.220  INFO 10275 --- [           main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-10-26 17:25:55.236 ERROR 10275 --- [           main] o.s.boot.SpringApplication               : Application run failed

java.lang.IllegalStateException: Failed to execute CommandLineRunner
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:783) ~[spring-boot-2.1.7.RELEASE.jar:2.1.7.RELEASE]
    at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:764) ~[spring-boot-2.1.7.RELEASE.jar:2.1.7.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:319) ~[spring-boot-2.1.7.RELEASE.jar:2.1.7.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1214) ~[spring-boot-2.1.7.RELEASE.jar:2.1.7.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1203) ~[spring-boot-2.1.7.RELEASE.jar:2.1.7.RELEASE]
    at com.example.accessingdatajpa.AccessingDataJpaApplication.main(AccessingDataJpaApplication.java:38) ~[classes/:na]
Caused by: java.lang.IllegalMonitorStateException: null
    at java.base/java.lang.Object.wait(Native Method) ~[na:na]
    at com.example.accessingdatajpa.AccessingDataJpaApplication.run(AccessingDataJpaApplication.java:71) ~[classes/:na]
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:780) ~[spring-boot-2.1.7.RELEASE.jar:2.1.7.RELEASE]
    ... 5 common frames omitted

2019-10-26 17:25:55.269  INFO 10275 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'
2019-10-26 17:25:55.270  INFO 10275 --- [           main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2019-10-26 17:25:55.278  INFO 10275 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2019-10-26 17:25:55.298  INFO 10275 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.

【问题讨论】:

  • 能否请您发布堆栈跟踪,我可以看到问题发生在哪里?
  • @SimonMartinelli 我已经用 stacktrace 更新了我的问题

标签: java spring spring-boot spring-data-jpa http-headers


【解决方案1】:

您需要在同步块中才能使 Object.wait() 工作。它在多线程环境中用于同步您的线程。但我假设您只是希望您的代码在记录最新结果之间稍等片刻。

请改用Thread.sleep(1000)

【讨论】:

    最近更新 更多