问:
NoSuchElementException on Session Factory bean creation and injection
I'm writing Spring Boot Application using Hibernate as ORM framework. Aftre writing some code my project works fine, but when i tried to add new entity to model application run fails with NoSuchElementException on creating SessionFactoryBean.

Tried to create a table in DB, but have no result. Removing @Entity annotation from new calss fixes the issue.

Hibernate Configuration class

```<code>@Configuration
@EnableTransactionManagement
public class HibernateConfiguration {

    @Bean(name = "mainSessionFactory")
    @Primary
    public LocalSessionFactoryBean mainSessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(mainDataSource());
        sessionFactory.setPackagesToScan("ua.edu.viti.medex.main");
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
    }

    @Bean(name = "mainDataSource")
    @Primary
    public DataSource mainDataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("org.postgresql.Driver");
        dataSource.setUrl("jdbc:postgresql://139.28.37.150:5432/main");
        dataSource.setUsername("application");
        dataSource.setPassword("application");
        return dataSource;
    }

    @Bean(name = "mainHibernateTransactionManager")
    @Primary
    public PlatformTransactionManager mainHibernateTransactionManager() {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager();
        transactionManager.setDataSource(mainDataSource());
        transactionManager.setSessionFactory(mainSessionFactory().getObject());
        return transactionManager;
    }

    private final Properties hibernateProperties() {
        Properties hibernateProperties = new Properties();
        hibernateProperties.setProperty("hibernate.hbm2ddl.auto", "update");
        hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQL94Dialect");
        return hibernateProperties;
    }

}
</code>```

Spring Application Initialzer Class

```<code>
public class MainInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext mainApplicationContext = new AnnotationConfigWebApplicationContext();
        servletContext.addListener(new ContextLoaderListener(mainApplicationContext));
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("main", new DispatcherServlet(mainApplicationContext));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");
    }
}

</code>```

New Class which I want to add

```<code>@Entity(name = "appeals")
public class Appeal implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id_appeal", nullable = false, updatable = false, unique = true)
    private Long id;
    @MapsId
    @OneToOne(fetch = FetchType.EAGER, targetEntity = Patient.class)
    private Patient patient;
    @Column(name = "appeal_date")
    private Date appeal;
    @Column(name = "appeal_essence")
    private String appealEssence;
    @Column(name = "is_first_appeal")
    private Boolean isFirstAppeal;

//getters/setters/constructors

</code>```

Class in which creating sessionFactory bean throws an exception

```<code>@Transactional(transactionManager = "mainHibernateTransactionManager", value = "mainHibernateTransactionManager")
@Service
public class PersonDAOImpl implements IPersonDAO {

    @Autowired
    @Qualifier("mainSessionFactory")
    SessionFactory mainSessionFactory;

    @Override
    public List<Person> getAllPersons() throws EmptyStackException {
        CriteriaBuilder cb = mainSessionFactory.getCriteriaBuilder();
        CriteriaQuery<Person> cquery = cb.createQuery(Person.class);
        Root<Person> root = cquery.from(Person.class);
        cquery.select(root);
        Query patientQuery = mainSessionFactory.getCurrentSession().createQuery(cquery);

        List<Person> searchedList = patientQuery.getResultList();
        if ((searchedList != null) || searchedList.size() != 0) {
            return searchedList;
        } else {
            throw new EmptyStackException();
        }
    }

    /**
     * find person by email with hibernate criteria query
     *
     * @param email email of person
     * @return searched person
     * @throws MalformedParametersException in case of malformed email
     */
    @Override
    public Person getPersonByEmail(String email) throws MalformedParametersException, NotFoundException {
        Matcher matcher = Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE).matcher(email);
        if (matcher.find()) {
            CriteriaBuilder cb = mainSessionFactory.getCriteriaBuilder();
            CriteriaQuery<Person> criteria = cb.createQuery(Person.class);
            Root<Person> root = criteria.from(Person.class);
            Predicate likeRestriction = cb.and(
                    cb.like(root.get("email"), email)
            );
            criteria.select(root).where(likeRestriction);
            TypedQuery<Person> typedQuery = mainSessionFactory.getCurrentSession().createQuery(criteria);
            return typedQuery.getSingleResult();
        } else {
            throw new MalformedParametersException("Wrong email!");
        }
    }

    @Override
    public Person getPersonById(Long id) throws NotFoundException {
        Person person = mainSessionFactory.getCurrentSession().get(Person.class, id);
        if (person == null) {
            throw new NotFoundException("Person not found");
        } else {
            return person;
        }
    }

    /**
     * signing up person then persists person
     * method persists person in database
     * encrypts password with Spring Security BCrypt password encoder
     *
     * @param person person to sign up
     * @return id of signed up person or -1 if person with such email already exists
     * @throws MalformedParametersException in case of wrong email pattern
     */

    @Override
    public Long signUpPerson(Person person) throws MalformedParametersException {
        Matcher matcher = Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE).matcher(person.getEmail());
        try {
            getPersonByEmail(person.getEmail());
        } catch (Exception e) {
            if (person.getEmail() != null && matcher.find()) {
                String unEcrPass = person.getPassword();
                person.setPassword(new BCryptPasswordEncoder().encode(unEcrPass));
                mainSessionFactory.getCurrentSession().persist(person);
                return person.getId();
            } else {
                throw new MalformedParametersException("Wrong email!");
            }
        }
        return -1L;
    }
</code>```

Application fails with this stack trace

```<code>
[ERROR] 2019-05-27 13:49:40.310 [main] SpringApplication - Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mainController': Unsatisfied dependency expressed through field 'personDAO'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'personDAOImpl': Unsatisfied dependency expressed through field 'mainSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mainSessionFactory' defined in class path resource [ua/edu/viti/medex/main/configuration/HibernateConfiguration.class]: Invocation of init method failed; nested exception is java.util.NoSuchElementException
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1378) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:575) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:846) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:863) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at ua.edu.viti.medex.main.MainApplication.main(MainApplication.java:13) [classes/:?]
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'personDAOImpl': Unsatisfied dependency expressed through field 'mainSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mainSessionFactory' defined in class path resource [ua/edu/viti/medex/main/configuration/HibernateConfiguration.class]: Invocation of init method failed; nested exception is java.util.NoSuchElementException
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1378) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:575) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:273) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1237) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1164) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    ... 19 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mainSessionFactory' defined in class path resource [ua/edu/viti/medex/main/configuration/HibernateConfiguration.class]: Invocation of init method failed; nested exception is java.util.NoSuchElementException
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1745) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:576) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:273) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1237) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1164) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1378) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:575) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:273) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1237) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1164) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    ... 19 more
Caused by: java.util.NoSuchElementException
    at java.util.ArrayList$Itr.next(ArrayList.java:862) ~[?:1.8.0_201]
    at org.hibernate.internal.util.collections.JoinedIterator.next(JoinedIterator.java:47) ~[hibernate-core-5.2.12.Final.jar:5.2.12.Final]
    at org.hibernate.cfg.annotations.TableBinder.linkJoinColumnWithValueOverridingNameIfImplicit(TableBinder.java:724) ~[hibernate-core-5.2.12.Final.jar:5.2.12.Final]
    at org.hibernate.cfg.PkDrivenByDefaultMapsIdSecondPass.doSecondPass(PkDrivenByDefaultMapsIdSecondPass.java:37) ~[hibernate-core-5.2.12.Final.jar:5.2.12.Final]
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1621) ~[hibernate-core-5.2.12.Final.jar:5.2.12.Final]
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1578) ~[hibernate-core-5.2.12.Final.jar:5.2.12.Final]
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:278) ~[hibernate-core-5.2.12.Final.jar:5.2.12.Final]
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83) ~[hibernate-core-5.2.12.Final.jar:5.2.12.Final]
    at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418) ~[hibernate-core-5.2.12.Final.jar:5.2.12.Final]
    at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87) ~[hibernate-core-5.2.12.Final.jar:5.2.12.Final]
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:691) ~[hibernate-core-5.2.12.Final.jar:5.2.12.Final]
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726) ~[hibernate-core-5.2.12.Final.jar:5.2.12.Final]
    at org.springframework.orm.hibernate5.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:615) ~[spring-orm-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.orm.hibernate5.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:599) ~[spring-orm-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1804) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1741) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:576) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:273) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1237) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1164) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1378) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:575) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:273) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1237) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1164) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    ... 19 more

</code>```

答: Found the solution. In new entity there is relation with another class of module. It marked as @MapsId annotation. But there is no id field in this class. It refers to another entity.

Body:
I'm writing Spring Boot Application using Hibernate as ORM framework. Aftre writing some code my project works fine, but when i tried to add new entity to model application run fails with NoSuchElementException on creating SessionFactoryBean.

Tried to create a table in DB, but have no result. Removing @Entity annotation from new calss fixes the issue.

Hibernate Configuration class

@Configuration
@EnableTransactionManagement
public class HibernateConfiguration {

    @Bean(name = "mainSessionFactory")
    @Primary
    public LocalSessionFactoryBean mainSessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(mainDataSource());
        sessionFactory.setPackagesToScan("ua.edu.viti.medex.main");
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
    }

    @Bean(name = "mainDataSource")
    @Primary
    public DataSource mainDataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("org.postgresql.Driver");
        dataSource.setUrl("jdbc:postgresql://139.28.37.150:5432/main");
        dataSource.setUsername("application");
        dataSource.setPassword("application");
        return dataSource;
    }

    @Bean(name = "mainHibernateTransactionManager")
    @Primary
    public PlatformTransactionManager mainHibernateTransactionManager() {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager();
        transactionManager.setDataSource(mainDataSource());
        transactionManager.setSessionFactory(mainSessionFactory().getObject());
        return transactionManager;
    }

    private final Properties hibernateProperties() {
        Properties hibernateProperties = new Properties();
        hibernateProperties.setProperty("hibernate.hbm2ddl.auto", "update");
        hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQL94Dialect");
        return hibernateProperties;
    }

}

Spring Application Initialzer Class

public class MainInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext mainApplicationContext = new AnnotationConfigWebApplicationContext();
        servletContext.addListener(new ContextLoaderListener(mainApplicationContext));
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("main", new DispatcherServlet(mainApplicationContext));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");
    }
}

New Class which I want to add

@Entity(name = "appeals")
public class Appeal implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id_appeal", nullable = false, updatable = false, unique = true)
    private Long id;
    @MapsId
    @OneToOne(fetch = FetchType.EAGER, targetEntity = Patient.class)
    private Patient patient;
    @Column(name = "appeal_date")
    private Date appeal;
    @Column(name = "appeal_essence")
    private String appealEssence;
    @Column(name = "is_first_appeal")
    private Boolean isFirstAppeal;

//getters/setters/constructors

Class in which creating sessionFactory bean throws an exception

@Transactional(transactionManager = "mainHibernateTransactionManager", value = "mainHibernateTransactionManager")
@Service
public class PersonDAOImpl implements IPersonDAO {

    @Autowired
    @Qualifier("mainSessionFactory")
    SessionFactory mainSessionFactory;

    @Override
    public List<Person> getAllPersons() throws EmptyStackException {
        CriteriaBuilder cb = mainSessionFactory.getCriteriaBuilder();
        CriteriaQuery<Person> cquery = cb.createQuery(Person.class);
        Root<Person> root = cquery.from(Person.class);
        cquery.select(root);
        Query patientQuery = mainSessionFactory.getCurrentSession().createQuery(cquery);

        List<Person> searchedList = patientQuery.getResultList();
        if ((searchedList != null) || searchedList.size() != 0) {
            return searchedList;
        } else {
            throw new EmptyStackException();
        }
    }

    /**
     * find person by email with hibernate criteria query
     *
     * @param email email of person
     * @return searched person
     * @throws MalformedParametersException in case of malformed email
     */
    @Override
    public Person getPersonByEmail(String email) throws MalformedParametersException, NotFoundException {
        Matcher matcher = Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE).matcher(email);
        if (matcher.find()) {
            CriteriaBuilder cb = mainSessionFactory.getCriteriaBuilder();
            CriteriaQuery<Person> criteria = cb.createQuery(Person.class);
            Root<Person> root = criteria.from(Person.class);
            Predicate likeRestriction = cb.and(
                    cb.like(root.get("email"), email)
            );
            criteria.select(root).where(likeRestriction);
            TypedQuery<Person> typedQuery = mainSessionFactory.getCurrentSession().createQuery(criteria);
            return typedQuery.getSingleResult();
        } else {
            throw new MalformedParametersException("Wrong email!");
        }
    }

    @Override
    public Person getPersonById(Long id) throws NotFoundException {
        Person person = mainSessionFactory.getCurrentSession().get(Person.class, id);
        if (person == null) {
            throw new NotFoundException("Person not found");
        } else {
            return person;
        }
    }

    /**
     * signing up person then persists person
     * method persists person in database
     * encrypts password with Spring Security BCrypt password encoder
     *
     * @param person person to sign up
     * @return id of signed up person or -1 if person with such email already exists
     * @throws MalformedParametersException in case of wrong email pattern
     */

    @Override
    public Long signUpPerson(Person person) throws MalformedParametersException {
        Matcher matcher = Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE).matcher(person.getEmail());
        try {
            getPersonByEmail(person.getEmail());
        } catch (Exception e) {
            if (person.getEmail() != null && matcher.find()) {
                String unEcrPass = person.getPassword();
                person.setPassword(new BCryptPasswordEncoder().encode(unEcrPass));
                mainSessionFactory.getCurrentSession().persist(person);
                return person.getId();
            } else {
                throw new MalformedParametersException("Wrong email!");
            }
        }
        return -1L;
    }

Application fails with this stack trace

[ERROR] 2019-05-27 13:49:40.310 [main] SpringApplication - Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mainController': Unsatisfied dependency expressed through field 'personDAO'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'personDAOImpl': Unsatisfied dependency expressed through field 'mainSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mainSessionFactory' defined in class path resource [ua/edu/viti/medex/main/configuration/HibernateConfiguration.class]: Invocation of init method failed; nested exception is java.util.NoSuchElementException
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1378) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:575) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:846) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:863) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at ua.edu.viti.medex.main.MainApplication.main(MainApplication.java:13) [classes/:?]
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'personDAOImpl': Unsatisfied dependency expressed through field 'mainSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mainSessionFactory' defined in class path resource [ua/edu/viti/medex/main/configuration/HibernateConfiguration.class]: Invocation of init method failed; nested exception is java.util.NoSuchElementException
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1378) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:575) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:273) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1237) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1164) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    ... 19 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mainSessionFactory' defined in class path resource [ua/edu/viti/medex/main/configuration/HibernateConfiguration.class]: Invocation of init method failed; nested exception is java.util.NoSuchElementException
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1745) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:576) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:273) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1237) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1164) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1378) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:575) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:273) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1237) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1164) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    ... 19 more
Caused by: java.util.NoSuchElementException
    at java.util.ArrayList$Itr.next(ArrayList.java:862) ~[?:1.8.0_201]
    at org.hibernate.internal.util.collections.JoinedIterator.next(JoinedIterator.java:47) ~[hibernate-core-5.2.12.Final.jar:5.2.12.Final]
    at org.hibernate.cfg.annotations.TableBinder.linkJoinColumnWithValueOverridingNameIfImplicit(TableBinder.java:724) ~[hibernate-core-5.2.12.Final.jar:5.2.12.Final]
    at org.hibernate.cfg.PkDrivenByDefaultMapsIdSecondPass.doSecondPass(PkDrivenByDefaultMapsIdSecondPass.java:37) ~[hibernate-core-5.2.12.Final.jar:5.2.12.Final]
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1621) ~[hibernate-core-5.2.12.Final.jar:5.2.12.Final]
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1578) ~[hibernate-core-5.2.12.Final.jar:5.2.12.Final]
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:278) ~[hibernate-core-5.2.12.Final.jar:5.2.12.Final]
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83) ~[hibernate-core-5.2.12.Final.jar:5.2.12.Final]
    at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418) ~[hibernate-core-5.2.12.Final.jar:5.2.12.Final]
    at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87) ~[hibernate-core-5.2.12.Final.jar:5.2.12.Final]
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:691) ~[hibernate-core-5.2.12.Final.jar:5.2.12.Final]
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726) ~[hibernate-core-5.2.12.Final.jar:5.2.12.Final]
    at org.springframework.orm.hibernate5.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:615) ~[spring-orm-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.orm.hibernate5.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:599) ~[spring-orm-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1804) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1741) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:576) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:273) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1237) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1164) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1378) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:575) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:273) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1237) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1164) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    ... 19 more


来源: stackexchange

问:
HttpHeaders not being set in the HTTPResponse
I am trying to implement the following the curl command in Java using teh DefaultHttpClient

```<code>curl  -H "Content-Type:application/json"  -H "Authorization:Bearer rAnDoMSrings-" -X POST -d  @example.json http://api.rest.company.com/
</code>```

Here is the client in Java

```<code>    DefaultHttpClient httpclient = null;
    HttpResponse response = null;

    try {
        httpclient = new DefaultHttpClient();
        HttpPost post = new HttpPost(apiUrl);
        post.setHeader("Content-Type","application/json");
        post.addHeader("Authorization", "Bearer " +authToken);
        JSONObject json = new JSONObject();
        json.put("image_url", ");
        // Required field.
        json.put("job_fqn",");
        JSONArray routesJsonArray = new JSONArray();
        routesJsonArray.put(0, "");
        json.put("routes",routesJsonArray);
        StringEntity params = new StringEntity(json.toString());
        post.setEntity(params);

        response = httpclient.execute(post);
    }
    catch (Exception e) {
        System.out.println("Exception" + e);
    }
    finally {
        httpclient.getConnectionManager().shutdown();
    }

}
</code>```

This gives a 401 Unauthorized error. Upon some debugging I found that none of the headers are being recognized and I get the follwoing

```<code>DEBUG [2016-06-30 14:24:16,559] org.apache.http.impl.client.DefaultHttpClient: Response contains no authentication challenges
</code>```

Note that the curl command works fine. What have I missed?

Note that the outgoing headers are set right and I can log them out of the request object

Here is teh stack trace

```<code>DEBUG [2016-06-30 17:51:08,665] org.apache.http.wire: >> "POST /v1/api HTTP/1.1[\r][\n]"
DEBUG [2016-06-30 17:51:08,665] org.apache.http.wire: >> "Content-Type: application/json[\r][\n]"
DEBUG [2016-06-30 17:51:08,666] org.apache.http.wire: >> "Authorization: Bearer correct_token; Path=/; Domain=auth.server; Expires=Fri, 01 Jul 2016 17:51:08 UTC[\r][\n]"
DEBUG [2016-06-30 17:51:08,666] org.apache.http.wire: >> "Content-Length: 320[\r][\n]"
DEBUG [2016-06-30 17:51:08,666] org.apache.http.wire: >> "Host: api.rest.company.com[\r][\n]"
DEBUG [2016-06-30 17:51:08,666] org.apache.http.wire: >> "Connection: Keep-Alive[\r][\n]"
DEBUG [2016-06-30 17:51:08,666] org.apache.http.wire: >> "User-Agent: Apache-HttpClient/4.2.6 (java 1.5)[\r][\n]"
DEBUG [2016-06-30 17:51:08,666] org.apache.http.wire: >> "[\r][\n]"
DEBUG [2016-06-30 17:51:08,666] org.apache.http.headers: >> POST /v1/jobs/docker HTTP/1.1
DEBUG [2016-06-30 17:51:08,666] org.apache.http.headers: >> Content-Type: application/json
DEBUG [2016-06-30 17:51:08,666] org.apache.http.headers: >> Authorization: Bearer correcttoken; Path=/; Domain=auth.server.com; Expires=Fri, 01 Jul 2016 17:51:08 UTC
DEBUG [2016-06-30 17:51:08,666] org.apache.http.headers: >> Content-Length: 320
DEBUG [2016-06-30 17:51:08,666] org.apache.http.headers: >> Host: api.rest.company.com
DEBUG [2016-06-30 17:51:08,666] org.apache.http.headers: >> Connection: Keep-Alive
DEBUG [2016-06-30 17:51:08,666] org.apache.http.headers: >> User-Agent: Apache-HttpClient/4.2.6 (java 1.5)
DEBUG [2016-06-30 17:51:08,666] org.apache.http.wire: >> "{"correct Json Entity"}"
DEBUG [2016-06-30 17:51:08,667] org.apache.http.wire: << "HTTP/1.1 401 Unauthorized[\r][\n]"
DEBUG [2016-06-30 17:51:08,667] org.apache.http.wire: << "Server: nginx[\r][\n]"
DEBUG [2016-06-30 17:51:08,668] org.apache.http.wire: << "Date: Thu, 30 Jun 2016 17:51:08 GMT[\r][\n]"
DEBUG [2016-06-30 17:51:08,668] org.apache.http.wire: << "Content-Type: application/json[\r][\n]"
DEBUG [2016-06-30 17:51:08,668] org.apache.http.wire: << "Content-Length: 62[\r][\n]"
DEBUG [2016-06-30 17:51:08,668] org.apache.http.wire: << "Connection: keep-alive[\r][\n]"
DEBUG [2016-06-30 17:51:08,668] org.apache.http.wire: << "Minimum-Apc-Version: 2.0.0[\r][\n]"
DEBUG [2016-06-30 17:51:08,668] org.apache.http.wire: << "[\r][\n]"
DEBUG [2016-06-30 17:51:08,668] org.apache.http.impl.conn.DefaultClientConnection: Receiving response: HTTP/1.1 401 Unauthorized
DEBUG [2016-06-30 17:51:08,668] org.apache.http.headers: << HTTP/1.1 401 Unauthorized
DEBUG [2016-06-30 17:51:08,668] org.apache.http.headers: << Server: nginx
DEBUG [2016-06-30 17:51:08,668] org.apache.http.headers: << Date: Thu, 30 Jun 2016 17:51:08 GMT
DEBUG [2016-06-30 17:51:08,668] org.apache.http.headers: << Content-Type: application/json
DEBUG [2016-06-30 17:51:08,668] org.apache.http.headers: << Content-Length: 62
DEBUG [2016-06-30 17:51:08,668] org.apache.http.headers: << Connection: keep-alive
DEBUG [2016-06-30 17:51:08,668] org.apache.http.headers: << Minimum-Apc-Version: 2.0.0
DEBUG [2016-06-30 17:51:08,668] org.apache.http.impl.client.DefaultHttpClient: Connection can be kept alive indefinitely
DEBUG [2016-06-30 17:51:08,668] org.apache.http.impl.client.DefaultHttpClient: Authentication required
DEBUG [2016-06-30 17:51:08,668] org.apache.http.impl.client.DefaultHttpClient: api.rest.company:80 requested authentication
DEBUG [2016-06-30 17:51:08,668] org.apache.http.impl.client.DefaultHttpClient: Response contains no authentication challenges
</code>```

Can it be related to the following two lines in the log

```<code>DEBUG [2016-06-30 17:51:08,665] org.apache.http.client.protocol.RequestAuthCache: Auth cache not set in the context
DEBUG [2016-06-30 17:51:08,665] org.apache.http.client.protocol.RequestProxyAuthentication: Proxy auth state: UNCHALLENGED
</code>```

Could it be that the header is lost after being redirected by the nginx proxy?

答:
I suppose the reason is you have used post.addHeader. Instead you should use post.setHeader. The code should be like the following from my point of view</p>

```<code>JSONObject json = new JSONObject();
json.put("image_url", "http://xx.xx");  // set the image_url parameter's value here
json.put("job_fqn", "xx");              // set the job_fqn parameter's value here
JSONArray routesJsonArray = new JSONArray();
routesJsonArray.put(0, "");
json.put("routes",routesJsonArray);

try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(API_URL);

        StringEntity params = new StringEntity(json.toString(), "UTF-8");
        httpPost.setHeader("Authorization", "Bearer " + authToken);
        httpPost.setHeader("Content-Type","application/json");
        httpPost.setEntity(params);

        final HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
        HttpConnectionParams.setSoTimeout(httpParams, 30000);
        httpPost.setParams(httpParams);

        LOGGER.debug("Request is being processed. HTTP Post: [" + EntityUtils.toString(httpPost.getEntity()) + "]");

        HttpResponse httpResponse = httpClient.execute(httpPost);

        String responseStr = EntityUtils.toString(httpResponse.getEntity());

        LOGGER.debug("Response String: " + responseStr);

        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            LOGGER.info("Request is successful!");
        } else {
            LOGGER.error("Request failed!");
            return -1;
        }
        return 0;
    } catch (ClientProtocolException cpe){
        LOGGER.error("ClientProtocolException while processing the request", cpe);
        return -1;
    }catch (SocketTimeoutException ste){
        LOGGER.error("SocketTimeoutException while processing the request", ste);
        return -1;
    }catch (IOException e){
        LOGGER.error("IOException while processing the request", e);
        return -1;
    }catch (Exception e){
        LOGGER.error("Exception while processing the request", e);
        return -1;
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to implement the following the curl command in Java using teh DefaultHttpClient

curl  -H "Content-Type:application/json"  -H "Authorization:Bearer rAnDoMSrings-" -X POST -d  @example.json http://api.rest.company.com/

Here is the client in Java

    DefaultHttpClient httpclient = null;
    HttpResponse response = null;

    try {
        httpclient = new DefaultHttpClient();
        HttpPost post = new HttpPost(apiUrl);
        post.setHeader("Content-Type","application/json");
        post.addHeader("Authorization", "Bearer " +authToken);
        JSONObject json = new JSONObject();
        json.put("image_url", ");
        // Required field.
        json.put("job_fqn",");
        JSONArray routesJsonArray = new JSONArray();
        routesJsonArray.put(0, "");
        json.put("routes",routesJsonArray);
        StringEntity params = new StringEntity(json.toString());
        post.setEntity(params);

        response = httpclient.execute(post);
    }
    catch (Exception e) {
        System.out.println("Exception" + e);
    }
    finally {
        httpclient.getConnectionManager().shutdown();
    }

}

This gives a 401 Unauthorized error. Upon some debugging I found that none of the headers are being recognized and I get the follwoing

DEBUG [2016-06-30 14:24:16,559] org.apache.http.impl.client.DefaultHttpClient: Response contains no authentication challenges

Note that the curl command works fine. What have I missed?

Note that the outgoing headers are set right and I can log them out of the request object

Here is teh stack trace

DEBUG [2016-06-30 17:51:08,665] org.apache.http.wire: >> "POST /v1/api HTTP/1.1[\r][\n]"
DEBUG [2016-06-30 17:51:08,665] org.apache.http.wire: >> "Content-Type: application/json[\r][\n]"
DEBUG [2016-06-30 17:51:08,666] org.apache.http.wire: >> "Authorization: Bearer correct_token; Path=/; Domain=auth.server; Expires=Fri, 01 Jul 2016 17:51:08 UTC[\r][\n]"
DEBUG [2016-06-30 17:51:08,666] org.apache.http.wire: >> "Content-Length: 320[\r][\n]"
DEBUG [2016-06-30 17:51:08,666] org.apache.http.wire: >> "Host: api.rest.company.com[\r][\n]"
DEBUG [2016-06-30 17:51:08,666] org.apache.http.wire: >> "Connection: Keep-Alive[\r][\n]"
DEBUG [2016-06-30 17:51:08,666] org.apache.http.wire: >> "User-Agent: Apache-HttpClient/4.2.6 (java 1.5)[\r][\n]"
DEBUG [2016-06-30 17:51:08,666] org.apache.http.wire: >> "[\r][\n]"
DEBUG [2016-06-30 17:51:08,666] org.apache.http.headers: >> POST /v1/jobs/docker HTTP/1.1
DEBUG [2016-06-30 17:51:08,666] org.apache.http.headers: >> Content-Type: application/json
DEBUG [2016-06-30 17:51:08,666] org.apache.http.headers: >> Authorization: Bearer correcttoken; Path=/; Domain=auth.server.com; Expires=Fri, 01 Jul 2016 17:51:08 UTC
DEBUG [2016-06-30 17:51:08,666] org.apache.http.headers: >> Content-Length: 320
DEBUG [2016-06-30 17:51:08,666] org.apache.http.headers: >> Host: api.rest.company.com
DEBUG [2016-06-30 17:51:08,666] org.apache.http.headers: >> Connection: Keep-Alive
DEBUG [2016-06-30 17:51:08,666] org.apache.http.headers: >> User-Agent: Apache-HttpClient/4.2.6 (java 1.5)
DEBUG [2016-06-30 17:51:08,666] org.apache.http.wire: >> "{"correct Json Entity"}"
DEBUG [2016-06-30 17:51:08,667] org.apache.http.wire: << "HTTP/1.1 401 Unauthorized[\r][\n]"
DEBUG [2016-06-30 17:51:08,667] org.apache.http.wire: << "Server: nginx[\r][\n]"
DEBUG [2016-06-30 17:51:08,668] org.apache.http.wire: << "Date: Thu, 30 Jun 2016 17:51:08 GMT[\r][\n]"
DEBUG [2016-06-30 17:51:08,668] org.apache.http.wire: << "Content-Type: application/json[\r][\n]"
DEBUG [2016-06-30 17:51:08,668] org.apache.http.wire: << "Content-Length: 62[\r][\n]"
DEBUG [2016-06-30 17:51:08,668] org.apache.http.wire: << "Connection: keep-alive[\r][\n]"
DEBUG [2016-06-30 17:51:08,668] org.apache.http.wire: << "Minimum-Apc-Version: 2.0.0[\r][\n]"
DEBUG [2016-06-30 17:51:08,668] org.apache.http.wire: << "[\r][\n]"
DEBUG [2016-06-30 17:51:08,668] org.apache.http.impl.conn.DefaultClientConnection: Receiving response: HTTP/1.1 401 Unauthorized
DEBUG [2016-06-30 17:51:08,668] org.apache.http.headers: << HTTP/1.1 401 Unauthorized
DEBUG [2016-06-30 17:51:08,668] org.apache.http.headers: << Server: nginx
DEBUG [2016-06-30 17:51:08,668] org.apache.http.headers: << Date: Thu, 30 Jun 2016 17:51:08 GMT
DEBUG [2016-06-30 17:51:08,668] org.apache.http.headers: << Content-Type: application/json
DEBUG [2016-06-30 17:51:08,668] org.apache.http.headers: << Content-Length: 62
DEBUG [2016-06-30 17:51:08,668] org.apache.http.headers: << Connection: keep-alive
DEBUG [2016-06-30 17:51:08,668] org.apache.http.headers: << Minimum-Apc-Version: 2.0.0
DEBUG [2016-06-30 17:51:08,668] org.apache.http.impl.client.DefaultHttpClient: Connection can be kept alive indefinitely
DEBUG [2016-06-30 17:51:08,668] org.apache.http.impl.client.DefaultHttpClient: Authentication required
DEBUG [2016-06-30 17:51:08,668] org.apache.http.impl.client.DefaultHttpClient: api.rest.company:80 requested authentication
DEBUG [2016-06-30 17:51:08,668] org.apache.http.impl.client.DefaultHttpClient: Response contains no authentication challenges

Can it be related to the following two lines in the log

DEBUG [2016-06-30 17:51:08,665] org.apache.http.client.protocol.RequestAuthCache: Auth cache not set in the context
DEBUG [2016-06-30 17:51:08,665] org.apache.http.client.protocol.RequestProxyAuthentication: Proxy auth state: UNCHALLENGED

Could it be that the header is lost after being redirected by the nginx proxy?

Body:
I suppose the reason is you have used post.addHeader. Instead you should use post.setHeader. The code should be like the following from my point of view

JSONObject json = new JSONObject();
json.put("image_url", "http://xx.xx");  // set the image_url parameter's value here
json.put("job_fqn", "xx");              // set the job_fqn parameter's value here
JSONArray routesJsonArray = new JSONArray();
routesJsonArray.put(0, "");
json.put("routes",routesJsonArray);

try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(API_URL);

        StringEntity params = new StringEntity(json.toString(), "UTF-8");
        httpPost.setHeader("Authorization", "Bearer " + authToken);
        httpPost.setHeader("Content-Type","application/json");
        httpPost.setEntity(params);

        final HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
        HttpConnectionParams.setSoTimeout(httpParams, 30000);
        httpPost.setParams(httpParams);

        LOGGER.debug("Request is being processed. HTTP Post: [" + EntityUtils.toString(httpPost.getEntity()) + "]");

        HttpResponse httpResponse = httpClient.execute(httpPost);

        String responseStr = EntityUtils.toString(httpResponse.getEntity());

        LOGGER.debug("Response String: " + responseStr);

        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            LOGGER.info("Request is successful!");
        } else {
            LOGGER.error("Request failed!");
            return -1;
        }
        return 0;
    } catch (ClientProtocolException cpe){
        LOGGER.error("ClientProtocolException while processing the request", cpe);
        return -1;
    }catch (SocketTimeoutException ste){
        LOGGER.error("SocketTimeoutException while processing the request", ste);
        return -1;
    }catch (IOException e){
        LOGGER.error("IOException while processing the request", e);
        return -1;
    }catch (Exception e){
        LOGGER.error("Exception while processing the request", e);
        return -1;
    }

ContentLicense: CC BY-SA 4.0


问:
how can i pass value from javascript to my php function codeigniter
Thank for help and attention.I'm apprentice

I tried this already

if i did it wrong way your can tell me anything.i learning. thanks.

checkfb() is a php function and outside script i want to call checkfb() in script function with pass javascript value.if in php looklike simply pass by value checkfb($fbFName,$fbLName,$Email); ?> but cant do cuz in script scope.i am sorry if i made your misunderstanding.

```<code>function checkLoginState() {
              FB.getLoginStatus(function(response) {
                  statusChangeCallback(response);
                    <?php $this->checkfb($fbFName,$fbLName,$Email); ?>
              });

public function checkfb($FName,$LName,$Email){

    print_r('checkfb') ; exit();
  }
  //code work for log in facebook already but i wanna add data into my database

function getCurrentUserInfo() {
<script>
              FB.api('/me?fields=first_name,last_name,email,link,gender,picture', function(userInfo) {

                  fbFName = userInfo.first_name;
                  fbLName = userInfo.last_name;
                  fbEmail = userInfo.email;
                  fbLink = userInfo.link;
                  fbGender = userInfo.gender;
                  fbpicture = userInfo.picture;
                  alert(fbID);
                  console.log(fbID);
                  console.log(fbFName);
                  console.log(fbLName);
                  console.log(fbEmail);

              });
          }
          function checkLoginState() {
              FB.getLoginStatus(function(response){
                  statusChangeCallback(response);
              });
          }
      </script>
</code>```

答: You need ajax to pass the value in PHP, That is the best way. </p>

Body:
Thank for help and attention.I'm apprentice

I tried this already

if i did it wrong way your can tell me anything.i learning. thanks.

checkfb() is a php function and outside script i want to call checkfb() in script function with pass javascript value.if in php looklike simply pass by value checkfb($fbFName,$fbLName,$Email); ?> but cant do cuz in script scope.i am sorry if i made your misunderstanding.

function checkLoginState() {
              FB.getLoginStatus(function(response) {
                  statusChangeCallback(response);
                    <?php $this->checkfb($fbFName,$fbLName,$Email); ?>
              });

public function checkfb($FName,$LName,$Email){

    print_r('checkfb') ; exit();
  }
  //code work for log in facebook already but i wanna add data into my database

function getCurrentUserInfo() {


问:
C# database update
I'm stuck on a little problem concerning database.

Once a month I get a XML file with customer information (Name, address, city,etc.). My primary key is a customer number which is provided in the XML file.

I have no trouble inserting the information in the database;

```<code>var cmd = new SqlCommand("insert into [customer_info]
   (customer_nr, firstname, lastname, address_1, address_2, address_3.......)");
//some code
cmd.ExecuteNonQuery();
</code>```

Now, I would like to update my table or just fill it with new information. How can I achieve this?

I've tried using TableAdapter but it does not work.

And I'm only permitted to add one XML because I can only have one customer_nr as primary key.

So basically how do I update or fill my table with new information?

Thanks.

答:
One way would be to bulk insert the data into a new staging table in the database (you could use SqlBulkCopy for this for optimal insert speed). Once it's in there, you could then index the customer_nr field and then run 2 statements:

```<code>-- UPDATE existing customers
UPDATE ci
SET ci.firstname = s.firstname,
    ci.lastname = s.lastname,
    ... etc
FROM StagingTable s
    INNER JOIN Customer_Info ci ON s.customer_nr = ci.customer_nr

-- INSERT new customers
INSERT Customer_Info (customer_nr, firstname, lastname, ....)
SELECT s.customer_nr, s.firstname, s.lastname, ....
FROM StagingTable s
    LEFT JOIN Customer_Info ci ON s.customer_nr = ci.customer_nr
WHERE ci.customer_nr IS NULL
</code>```

Finally, drop your staging table.

Alternatively, instead of the 2 statements, you could just use the MERGE statement if you are using SQL Server 2008 or later, which allows you to do INSERTs and UPDATEs via a single statement.

Title: C# database update

Body:
I'm stuck on a little problem concerning database.

Once a month I get a XML file with customer information (Name, address, city,etc.). My primary key is a customer number which is provided in the XML file.

I have no trouble inserting the information in the database;

var cmd = new SqlCommand("insert into [customer_info]
   (customer_nr, firstname, lastname, address_1, address_2, address_3.......)");
//some code
cmd.ExecuteNonQuery();

Now, I would like to update my table or just fill it with new information. How can I achieve this?

I've tried using TableAdapter but it does not work.

And I'm only permitted to add one XML because I can only have one customer_nr as primary key.

So basically how do I update or fill my table with new information?

Thanks.

Body:
One way would be to bulk insert the data into a new staging table in the database (you could use SqlBulkCopy for this for optimal insert speed). Once it's in there, you could then index the customer_nr field and then run 2 statements:

-- UPDATE existing customers
UPDATE ci
SET ci.firstname = s.firstname,
    ci.lastname = s.lastname,
    ... etc
FROM StagingTable s
    INNER JOIN Customer_Info ci ON s.customer_nr = ci.customer_nr

-- INSERT new customers
INSERT Customer_Info (customer_nr, firstname, lastname, ....)
SELECT s.customer_nr, s.firstname, s.lastname, ....
FROM StagingTable s
    LEFT JOIN Customer_Info ci ON s.customer_nr = ci.customer_nr
WHERE ci.customer_nr IS NULL

Finally, drop your staging table.

Alternatively, instead of the 2 statements, you could just use the MERGE statement if you are using SQL Server 2008 or later, which allows you to do INSERTs and UPDATEs via a single statement.


问:
object dynamic filtering with nested array of objects using javascript
i have this data sample,

```<code>{
    "section": [
        {
            "id": 1,
            "name" : "dogs"
        },
        {
            "id": 2,
            "name" : "cats"
        }
    ],
    "price" : [
        {

            "name" : "monthly",
            "price": {
                "amount": 10
            }
        }
    ],
    "specs": {
        "color" : {
            "name" : "green"
        }
    }
}
</code>```

i want to pick some properties from that object, like that

```<code>const obj = pick(obj,["section.id","price.price"])
</code>```

it should gives an object:

```<code>{
    "section": [
        {
            "id": 1,
        },
        {
            "id": 2,
        }
    ],
    "price" : [
        {
            "price": {
                "amount": 10
            }
        }
    ],
}
</code>```

i tried lodash.pick() and didn't understand the array of object case, it understand it if i used this syntax "section[0].name" and i want it generic, like "section.name"

答:
You could take a custom pick function which take the wanted properties and takes all nested arrays without being part of the pathes.

function pick(object, keys) {
    if (Array.isArray(object)) return object.map(o => pick(o, keys));
    var pathes = keys.reduce((r, key) => {
        var [k, ...rest] = key.split('.'),
            temp = r.find(([l]) => k === l),
            left = rest.join('.');

        if (!(k in object)) return r;
        if (!temp) r.push(temp = [k, []]);
        if (left) temp[1].push(left);
        return r;
    }, []);
    return Object.assign({}, ...pathes.map(([k, rest]) => ({ [k]: rest.length
        ? pick(object[k], rest)
        : object[k]
    })));
}

var data = { section: [{ id: 1, name: "dogs" }, { id: 2, name: "cats" }], price: [{ name: "monthly", price: { amount: 10 } }], specs: { color: { name: "green" } } },
    result = pick(data, ["section.id", "price.price"]);

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
i have this data sample,

{
    "section": [
        {
            "id": 1,
            "name" : "dogs"
        },
        {
            "id": 2,
            "name" : "cats"
        }
    ],
    "price" : [
        {

            "name" : "monthly",
            "price": {
                "amount": 10
            }
        }
    ],
    "specs": {
        "color" : {
            "name" : "green"
        }
    }
}

i want to pick some properties from that object, like that

const obj = pick(obj,["section.id","price.price"])

it should gives an object:

{
    "section": [
        {
            "id": 1,
        },
        {
            "id": 2,
        }
    ],
    "price" : [
        {
            "price": {
                "amount": 10
            }
        }
    ],
}

i tried lodash.pick() and didn't understand the array of object case, it understand it if i used this syntax "section[0].name" and i want it generic, like "section.name"

Body:
You could take a custom pick function which take the wanted properties and takes all nested arrays without being part of the pathes.

function pick(object, keys) {
    if (Array.isArray(object)) return object.map(o => pick(o, keys));
    var pathes = keys.reduce((r, key) => {
        var [k, ...rest] = key.split('.'),
            temp = r.find(([l]) => k === l),
            left = rest.join('.');

        if (!(k in object)) return r;
        if (!temp) r.push(temp = [k, []]);
        if (left) temp[1].push(left);
        return r;
    }, []);
    return Object.assign({}, ...pathes.map(([k, rest]) => ({ [k]: rest.length
        ? pick(object[k], rest)
        : object[k]
    })));
}

var data = { section: [{ id: 1, name: "dogs" }, { id: 2, name: "cats" }], price: [{ name: "monthly", price: { amount: 10 } }], specs: { color: { name: "green" } } },
    result = pick(data, ["section.id", "price.price"]);

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Using Docker as service registry for microservices
I've followed some tutorial that walks through setting up 3 microservices (app, products and feedback) and 1 service registry.

After working with Docker for a while I feel the service registry is redundant. Because Docker can kick instances while injecting hostnames and ports via environment variables to each other.

For instance in the following Docker Compose file, I'm passing db credentials from a MySQL microservice to Node.js microservice and in the similar way, if there were other Node.js microservices, I could wire them up.

```<code>version: '3'

services:

  mysql:
    image: "mysql:5.7"
    container_name: "mysql"
    ports:
      - "6603:3306"
    volumes:
      - ./assets/schema.sql:/docker-entrypoint-initdb.d/init.sql
    environment:
      DATABASE_HOST: mysql
      MYSQL_ROOT_PASSWORD: rootpass
      MYSQL_DATABASE: database
      MYSQL_USER: mysql
      MYSQL_PASSWORD: password

  products_service:
    build: .
    command: bash -c "/wait && npm start"
    volumes:
      - "./src/:/service/src/"
    image: "node"
    container_name: "products"
    ports:
      - "8080:8080"
    depends_on:
      - mysql
    environment:
      DATABASE_HOST: mysql
      MYSQL_PORT: 3306
      MYSQL_DATABASE: database
      MYSQL_USER: mysql
      MYSQL_PASSWORD: password
      WAIT_HOSTS: mysql:3306
    restart: on-failure
</code>```

Do I really need to code and program a registry service in Node.js?

答:
Assuming your product service exposes rest endpoints which external world uses https://myserver/myservice.

After some time your product service became very popular and you want to scale it further without breaking current contract(the endpoint above).

To scale your product service  you will start more than one instance which are running on same or different host(s).

The service that keeps track of how many instance of your product service is running is called discovery service.

This is not enough outside traffic that is coming to your service endpoint should be routed to all the instances of your product services. That is the job of API gateway which acts like a reverse proxy. You can specify policy such as round robin to route traffic to all the instances.

Thus API gateway and service discovery together provides scalability and fault tolerance for your service.

References-

https://learn.microsoft.com/en-us/dotnet/standard/microservices-architecture/architect-microservice-container-applications/direct-client-to-microservice-communication-versus-the-api-gateway-pattern

https://auth0.com/blog/an-introduction-to-microservices-part-3-the-service-registry/

Body:
I've followed some tutorial that walks through setting up 3 microservices (app, products and feedback) and 1 service registry.

After working with Docker for a while I feel the service registry is redundant. Because Docker can kick instances while injecting hostnames and ports via environment variables to each other.

For instance in the following Docker Compose file, I'm passing db credentials from a MySQL microservice to Node.js microservice and in the similar way, if there were other Node.js microservices, I could wire them up.

version: '3'

services:

  mysql:
    image: "mysql:5.7"
    container_name: "mysql"
    ports:
      - "6603:3306"
    volumes:
      - ./assets/schema.sql:/docker-entrypoint-initdb.d/init.sql
    environment:
      DATABASE_HOST: mysql
      MYSQL_ROOT_PASSWORD: rootpass
      MYSQL_DATABASE: database
      MYSQL_USER: mysql
      MYSQL_PASSWORD: password

  products_service:
    build: .
    command: bash -c "/wait && npm start"
    volumes:
      - "./src/:/service/src/"
    image: "node"
    container_name: "products"
    ports:
      - "8080:8080"
    depends_on:
      - mysql
    environment:
      DATABASE_HOST: mysql
      MYSQL_PORT: 3306
      MYSQL_DATABASE: database
      MYSQL_USER: mysql
      MYSQL_PASSWORD: password
      WAIT_HOSTS: mysql:3306
    restart: on-failure

Do I really need to code and program a registry service in Node.js?


问:
const can only be used in a .ts file react native
```<code>const ACCESS_TOKEN = 'access_token';

react-native-cli: 2.0.1
react-native: 0.47.2
</code>```

I am watching a tutorial video in which the expert get the value from the api and stored it inside the const ACCESS_TOKEN but when i am doing it in my code it gives me an error

const can only be used in a .ts file react native

Please suggest.

答: The const is inside a class, move it outside of the class and the error will disappear.</p>

Body:
const ACCESS_TOKEN = 'access_token';

react-native-cli: 2.0.1
react-native: 0.47.2

I am watching a tutorial video in which the expert get the value from the api and stored it inside the const ACCESS_TOKEN but when i am doing it in my code it gives me an error

const can only be used in a .ts file react native

Please suggest.


问:
Unity - How can i make a function fire only when player clicked on it 3 times?
I have a hint button on my game, but it fires up everytime you click on it. I need for it to fire only once every 3 clicks

i've tried adding a loadCount = 0 and an if statement

```<code>if (loadCount % 3 == 0) { }
</code>```

but it dosen't seem to work

image for reference : https://ibb.co/L9LnNDw

Here is the script:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[ExecuteInEditMode]
public class HintScript : MonoBehaviour
{

    LineRenderer line;

    // Use this for initialization
    void Start ()
    {

    }

    // Update is called once per frame
    void Update ()
    {
        line = GetComponent<LineRenderer>();
        line.positionCount = transform.childCount;
        for (int i = 0; i<transform.childCount; i++)
        {
            line.SetPosition(i, transform.GetChild(i).position);
        }
    }

    // This is called from onClick of the Button
    public void Hint()
    {
        FindObjectOfType<AdMobManager>().Hint = true;
        FindObjectOfType<AdMobManager>().showInterstitial();
    }
}
</code>```

答:
You should use a simply counter.

I also changed and commented other "issues" in your code:

```<code>public class HintScript : MonoBehaviour
{
    // by adding SerializeField you can already set those references
    // directly in the Unity Editor. This is better than getting them at runtime.
    [SerializeField] private LineRenderer line;
    [SerializeField] private AdMobManager adMobManager;
    // you can still change the required clicks in the inspector
    // Note: afterwards changing it here will have no effect!
    [SerializeField] private int requiredClicks = 3;

    // counter for your clicks
    private int counter;

    // Use this for initialization
    void Start ()
    {
        // you should do this only once
        line = GetComponent<LineRenderer>();

        // you should also this only do once
        adMobManager = FindObjectOfType<AdMobManager>();

        // If instead you would drag those references directly into the now
        // serialized fields you wouldn't have to get them on runtime at all.
    }

    // Update is called once per frame
    void Update ()
    {
        line.positionCount = transform.childCount;
        var positions = new Vector3[transform.childCount];
        for (var i = 0; i < transform.childCount; i++)
        {
            position[i] = transform.GetChild(i).position;
        }

        // it is more efficient to call this only once
        // see https://docs.unity3d.com/ScriptReference/LineRenderer.SetPositions.html
        line.SetPositions(positions);
    }

    // This is called from onClick of the Button
    public void Hint()
    {
        counter++;

        if(counter < requiredClicks) return;

        // Or using your solution should actually also work
        if(counter % requiredClicks != 0) return;

        adMobManager.Hint = true;
        adMobManager.showInterstitial();

        // reset the counter
        counter = 0;
    }
}
</code>```

Body:
I have a hint button on my game, but it fires up everytime you click on it. I need for it to fire only once every 3 clicks

i've tried adding a loadCount = 0 and an if statement

if (loadCount % 3 == 0) { }

but it dosen't seem to work

image for reference : https://ibb.co/L9LnNDw

Here is the script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[ExecuteInEditMode]
public class HintScript : MonoBehaviour
{

    LineRenderer line;

    // Use this for initialization
    void Start ()
    {

    }

    // Update is called once per frame
    void Update ()
    {
        line = GetComponent<LineRenderer>();
        line.positionCount = transform.childCount;
        for (int i = 0; i<transform.childCount; i++)
        {
            line.SetPosition(i, transform.GetChild(i).position);
        }
    }

    // This is called from onClick of the Button
    public void Hint()
    {
        FindObjectOfType<AdMobManager>().Hint = true;
        FindObjectOfType<AdMobManager>().showInterstitial();
    }
}

Body:
You should use a simply counter.

I also changed and commented other "issues" in your code:

public class HintScript : MonoBehaviour
{
    // by adding SerializeField you can already set those references
    // directly in the Unity Editor. This is better than getting them at runtime.
    [SerializeField] private LineRenderer line;
    [SerializeField] private AdMobManager adMobManager;
    // you can still change the required clicks in the inspector
    // Note: afterwards changing it here will have no effect!
    [SerializeField] private int requiredClicks = 3;

    // counter for your clicks
    private int counter;

    // Use this for initialization
    void Start ()
    {
        // you should do this only once
        line = GetComponent<LineRenderer>();

        // you should also this only do once
        adMobManager = FindObjectOfType<AdMobManager>();

        // If instead you would drag those references directly into the now
        // serialized fields you wouldn't have to get them on runtime at all.
    }

    // Update is called once per frame
    void Update ()
    {
        line.positionCount = transform.childCount;
        var positions = new Vector3[transform.childCount];
        for (var i = 0; i < transform.childCount; i++)
        {
            position[i] = transform.GetChild(i).position;
        }

        // it is more efficient to call this only once
        // see https://docs.unity3d.com/ScriptReference/LineRenderer.SetPositions.html
        line.SetPositions(positions);
    }

    // This is called from onClick of the Button
    public void Hint()
    {
        counter++;

        if(counter < requiredClicks) return;

        // Or using your solution should actually also work
        if(counter % requiredClicks != 0) return;

        adMobManager.Hint = true;
        adMobManager.showInterstitial();

        // reset the counter
        counter = 0;
    }
}


问:
How to set the checkpoint for fine-tuning
I found the loss when I retrain the model(ssd_mobilenetv2) from model_zoo is very large at the begining of training, While the accuracy on validation_set is good. Training log as below:

The log couldn't be from the trained model. I doubt it doesn't load the checkpoint to do the fine-tune. Please help me how to do the fine-tune with the trained model on the same dataset. I didn't modify the network structure at all.

I set the checkpoint path in pipeline.config as below:
fine_tune_checkpoint:"//ssd_mobilenet_v2_coco_2018_03_29/model.ckpt"
If I set the model_dir as my downloaded directory, It wouldn't train since the global_train_step is larger than max_step. Then I enlarge the max_step, I can see the log of restoring the parameter from checkpoint. But it would meet error that couldn't restore some parameter.
So I set the model_dir to a empty directory. It could train normally but the loss in step0 would be very large. And the validation result is very bad

in pipeline.config

```<code>fine_tune_checkpoint: "/ssd_mobilenet_v2_coco_2018_03_29/model.ckpt"
num_steps: 200000
fine_tune_checkpoint_type: "detection"
</code>```

train script

```<code>model_dir = '/ssd_mobilenet_v2_coco_2018_03_29/retrain0524

pipeline_config_path = '/ssd_mobilenet_v2_coco_2018_03_29/pipeline.config'

checkpoint_dir = '/ssd_mobilenet_v2_coco_2018_03_29/model.ckpt'

num_train_steps = 300000
config = tf.estimator.RunConfig(model_dir=model_dir)
train_and_eval_dict = model_lib.create_estimator_and_inputs(
    run_config=config,
    hparams=model_hparams.create_hparams(hparams_overrides),
    pipeline_config_path=pipeline_config_path,
    sample_1_of_n_eval_examples=sample_1_of_n_eval_examples,
    sample_1_of_n_eval_on_train_examples=(sample_1_of_n_eval_on_train_examples))
estimator = train_and_eval_dict['estimator']
train_input_fn = train_and_eval_dict['train_input_fn']
eval_input_fns = train_and_eval_dict['eval_input_fns']
eval_on_train_input_fn = train_and_eval_dict['eval_on_train_input_fn']
predict_input_fn = train_and_eval_dict['predict_input_fn']
train_steps = train_and_eval_dict['train_steps']

train_spec, eval_specs = model_lib.create_train_and_eval_specs(
        train_input_fn,
        eval_input_fns,
        eval_on_train_input_fn,
        predict_input_fn,
        train_steps,
        eval_on_train_data=False)

tf.estimator.train_and_evaluate(estimator, train_spec, eval_specs[0])
</code>```

INFO:tensorflow:loss = 356.25497, step = 0
INFO:tensorflow:global_step/sec: 1.89768
INFO:tensorflow:loss = 11.221423, step = 100 (52.700 sec)
INFO:tensorflow:global_step/sec: 2.21685
INFO:tensorflow:loss = 10.329516, step = 200 (45.109 sec)

答:
If the initial training loss is 400, the model most likely is restored from a checkpoint successfully, just not all the same as the checkpoint.

Here is the restore_map function of ssd models, note that even if you set fine_tune_checkpoint_type : detection and even provided with exactly the same model's checkpoint, still only the variables in the feature_extractor scope are restored. To restore as much variables from the checkpoint as possible, you will have to set load_all_detection_checkpoint_vars: true in your config file.

```<code>def restore_map(self,
              fine_tune_checkpoint_type='detection',
              load_all_detection_checkpoint_vars=False):

if fine_tune_checkpoint_type not in ['detection', 'classification']:
  raise ValueError('Not supported fine_tune_checkpoint_type: {}'.format(
      fine_tune_checkpoint_type))

if fine_tune_checkpoint_type == 'classification':
  return self._feature_extractor.restore_from_classification_checkpoint_fn(
      self._extract_features_scope)

if fine_tune_checkpoint_type == 'detection':
  variables_to_restore = {}
  for variable in tf.global_variables():
    var_name = variable.op.name
    if load_all_detection_checkpoint_vars:
      variables_to_restore[var_name] = variable
    else:
      if var_name.startswith(self._extract_features_scope):
        variables_to_restore[var_name] = variable

return variables_to_restore
</code>```

Body:
I found the loss when I retrain the model(ssd_mobilenetv2) from model_zoo is very large at the begining of training, While the accuracy on validation_set is good. Training log as below:

The log couldn't be from the trained model. I doubt it doesn't load the checkpoint to do the fine-tune. Please help me how to do the fine-tune with the trained model on the same dataset. I didn't modify the network structure at all.

I set the checkpoint path in pipeline.config as below:
fine_tune_checkpoint:"//ssd_mobilenet_v2_coco_2018_03_29/model.ckpt"
If I set the model_dir as my downloaded directory, It wouldn't train since the global_train_step is larger than max_step. Then I enlarge the max_step, I can see the log of restoring the parameter from checkpoint. But it would meet error that couldn't restore some parameter.
So I set the model_dir to a empty directory. It could train normally but the loss in step0 would be very large. And the validation result is very bad

in pipeline.config

fine_tune_checkpoint: "/ssd_mobilenet_v2_coco_2018_03_29/model.ckpt"
num_steps: 200000
fine_tune_checkpoint_type: "detection"

train script

model_dir = '/ssd_mobilenet_v2_coco_2018_03_29/retrain0524

pipeline_config_path = '/ssd_mobilenet_v2_coco_2018_03_29/pipeline.config'

checkpoint_dir = '/ssd_mobilenet_v2_coco_2018_03_29/model.ckpt'

num_train_steps = 300000
config = tf.estimator.RunConfig(model_dir=model_dir)
train_and_eval_dict = model_lib.create_estimator_and_inputs(
    run_config=config,
    hparams=model_hparams.create_hparams(hparams_overrides),
    pipeline_config_path=pipeline_config_path,
    sample_1_of_n_eval_examples=sample_1_of_n_eval_examples,
    sample_1_of_n_eval_on_train_examples=(sample_1_of_n_eval_on_train_examples))
estimator = train_and_eval_dict['estimator']
train_input_fn = train_and_eval_dict['train_input_fn']
eval_input_fns = train_and_eval_dict['eval_input_fns']
eval_on_train_input_fn = train_and_eval_dict['eval_on_train_input_fn']
predict_input_fn = train_and_eval_dict['predict_input_fn']
train_steps = train_and_eval_dict['train_steps']

train_spec, eval_specs = model_lib.create_train_and_eval_specs(
        train_input_fn,
        eval_input_fns,
        eval_on_train_input_fn,
        predict_input_fn,
        train_steps,
        eval_on_train_data=False)

tf.estimator.train_and_evaluate(estimator, train_spec, eval_specs[0])

INFO:tensorflow:loss = 356.25497, step = 0
INFO:tensorflow:global_step/sec: 1.89768
INFO:tensorflow:loss = 11.221423, step = 100 (52.700 sec)
INFO:tensorflow:global_step/sec: 2.21685
INFO:tensorflow:loss = 10.329516, step = 200 (45.109 sec)

Body:
If the initial training loss is 400, the model most likely is restored from a checkpoint successfully, just not all the same as the checkpoint.

Here is the restore_map function of ssd models, note that even if you set fine_tune_checkpoint_type : detection and even provided with exactly the same model's checkpoint, still only the variables in the feature_extractor scope are restored. To restore as much variables from the checkpoint as possible, you will have to set load_all_detection_checkpoint_vars: true in your config file.

def restore_map(self,
              fine_tune_checkpoint_type='detection',
              load_all_detection_checkpoint_vars=False):

if fine_tune_checkpoint_type not in ['detection', 'classification']:
  raise ValueError('Not supported fine_tune_checkpoint_type: {}'.format(
      fine_tune_checkpoint_type))

if fine_tune_checkpoint_type == 'classification':
  return self._feature_extractor.restore_from_classification_checkpoint_fn(
      self._extract_features_scope)

if fine_tune_checkpoint_type == 'detection':
  variables_to_restore = {}
  for variable in tf.global_variables():
    var_name = variable.op.name
    if load_all_detection_checkpoint_vars:
      variables_to_restore[var_name] = variable
    else:
      if var_name.startswith(self._extract_features_scope):
        variables_to_restore[var_name] = variable

return variables_to_restore


问:
How to check if all TextBoxes on an Excel UserForm are filled?
I have bunch of input TextBoxes. I need to check all TextBoxes are filled before processing. Since I have 17 TextBoxes, can any one help me to write a code to check all.

I have tried by using If ... Then ... Else but it seems not working in my case.

答:
You can …

… loop through all controls

```<code>For Each Ctrl In Me.Controls
</code>```

… then check if the current control is a TextBox

```<code>If TypeName(Ctrl) = "TextBox" Then
</code>```

… and then check if it is empty

```<code>If Ctrl.Text = vbNullString Then
</code>```

So you end up with something like this:

```<code>Option Explicit

Public Sub ValidateCheckBoxes()
    Dim EmptyBoxesFound As Boolean

    Dim Ctrl As Control
    For Each Ctrl In Me.Controls
        If TypeName(Ctrl) = "TextBox" Then
            If Ctrl.Text = vbNullString Then
                EmptyBoxesFound = True
                Exit For
            End If
        End If
    Next Ctrl

    If EmptyBoxesFound Then
        MsgBox "At least one box is not filled.", vbExclamation
    Else
        MsgBox "All boxes are filled.", vbInformation
    End If
End Sub
</code>```

Body:
You can …

… loop through all controls

For Each Ctrl In Me.Controls

… then check if the current control is a TextBox

If TypeName(Ctrl) = "TextBox" Then

… and then check if it is empty

If Ctrl.Text = vbNullString Then

So you end up with something like this:

Option Explicit

Public Sub ValidateCheckBoxes()
    Dim EmptyBoxesFound As Boolean

    Dim Ctrl As Control
    For Each Ctrl In Me.Controls
        If TypeName(Ctrl) = "TextBox" Then
            If Ctrl.Text = vbNullString Then
                EmptyBoxesFound = True
                Exit For
            End If
        End If
    Next Ctrl

    If EmptyBoxesFound Then
        MsgBox "At least one box is not filled.", vbExclamation
    Else
        MsgBox "All boxes are filled.", vbInformation
    End If
End Sub