Проблема с опросом для вставок в БД - PullRequest
0 голосов
/ 16 апреля 2019

Я хочу внедрить службу опроса, которая должна обращаться к определенной таблице для получения последних записей, вставленных из любого другого приложения, или может быть с помощью прямого запроса вставки в подсказке SQL.Он должен слушать таблицу для всех вставок, или я должен нажимать на таблицу каждые несколько секунд, чтобы получить новые записи.Пожалуйста, помогите мне, как добиться этого, путем опроса службы ИЛИ прослушивателя ИЛИ многопоточности.

Я создал прослушиватель, как показано ниже: -

@Component
public class SMSListener implements ApplicationListener<ApplicationEvent>, PostInsertEventListener{

@Autowired
SMSServiceImpl serviceImpl;

@Autowired
SendSMS sendSMS;

public SMSListener() {

}

@Override
public boolean requiresPostCommitHanding(EntityPersister persister) {
    // TODO Auto-generated method stub
    return false;
}

@Override
public void onPostInsert(PostInsertEvent event) {
    log.debug("Entering SMSListener:onPostInsert:::::::::::::::");

    try {
        sendSMS.sendSMSes();
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }       
}

@Override
public void onApplicationEvent(ApplicationEvent event) {
     System.out.println("event: " + event);              
}}      

и один класс EntityEventListenerRegistry: -

 @Component
 public class EntityEventListenerRegistry {

private static final Logger logger = LoggerFactory.getLogger(
                        EntityEventListenerRegistry.class);

private static SessionFactory sessionFactory;

public static SessionFactory getSessionFactory() {
    return buildSessionFactory();
}

private static SessionFactory buildSessionFactory() {
    SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
    return sessionFactory; 
}

/**
 * EventListenerRegistry:
 * http://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/
 * Hibernate_User_Guide.html#annotations-jpa-entitylisteners
 */
@SuppressWarnings("unchecked")
@PostConstruct
public void registerListeners(){
    logger.info("Registering event listeners::::::::::::::::::");        
    EventListenerRegistry eventListenerRegistry = ((SessionFactoryImplementor)sessionFactory.getSessionFactory()).
            getServiceRegistry().getService(EventListenerRegistry.class);
    eventListenerRegistry.appendListeners(EventType.POST_INSERT, SMSListener.class);

}}               

и ниже запись слушателя в классе модели: -

   @Entity
   @Table(name = "ozekimessageout", schema = "dbo")
   @EntityListeners(SMSListener.class)
   public class SMSOutgoing implements Serializable 

и приложения, основные методы: -

  @SpringBootApplication(scanBasePackages = "com.avaal.sms.*", exclude= 
  {HibernateJpaAutoConfiguration.class})
  @Configuration
  @EnableJpaRepositories(basePackages = "com.avaal.sms.*")
  @ComponentScan
  @EnableAutoConfiguration 
 public static void main(String[] args) throws PlivoXmlException {
 SpringApplication application = new SpringApplication();
 application.addListeners(new SMSListener());
 SpringApplication.run(Application.class, args);     

, но я получаю ошибку при запускеэтот код: -

 05:38:05.787 [main] INFO  o.h.jpa.internal.util.LogHelper - HHH000204: 
 Processing PersistenceUnitInfo [
 name: default
...]
 05:38:05.829 [main] WARN  o.s.w.c.s.GenericWebApplicationContext - 
 Exception encountered during context initialization - cancelling refresh 
 attempt: org.springframework.beans.factory.BeanCreationException: Error 
 creating bean with name 'entityManagerFactory' defined in class path 
 resource         [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class] 
: Invocation of init method failed; nested exception is 
java.util.ServiceConfigurationError: 
org.hibernate.integrator.spi.Integrator: Provider 
org.hibernate.ejb.event.JpaIntegrator not found
 05:38:05.845 [main] INFO  
o.s.b.a.l.ConditionEvaluationReportLoggingListener - 

Error starting ApplicationContext. To display the conditions report re-run 
your application with 'debug' enabled.
 05:38:05.845 [main] ERROR o.s.boot.SpringApplication - Application run 
failed
org.springframework.beans.factory.BeanCreationException: Error creating bean 
with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is java.util.ServiceConfigurationError: org.hibernate.integrator.spi.Integrator: Provider org.hibernate.ejb.event.JpaIntegrator not found
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1762)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean      
...