我在我的应用程序中使用jpa进行数据库连接 . 但现在我想使用java代码获取entityManager . 所以我使用此代码创建entityManager:

public static EntityManager entityManagerFactory(String dbName){

LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();

   entityManagerFactory.setPersistenceUnitName(dbName);

  entityManagerFactory.setJpaVendorAdapter(new HibernateJpaVendorAdapter());

  entityManagerFactory.setJpaDialect(new HibernateJpaDialect());

 entityManagerFactory.setPackagesToScan("com.howtodoinjava.demo.model");

 entityManagerFactory.setJpaPropertyMap(hibernateJpaProperties(dbName));

 entityManagerFactory.afterPropertiesSet();

  JpaTransactionManager jpaTransactionManager=transactionManager(entityManagerFactory.getObject());

return jpaTransactionManager.getEntityManagerFactory().createEntityManager();

}

并在这里设置hibernate与每个数据库对应的Jpa Properties:

private static  Map<String, ?> hibernateJpaProperties(String dbName) {
HashMap<String, String> properties = new HashMap<String, String>();
properties.put("javax.persistence.transactionType", "RESOURCE_LOCAL");
properties.put("hibernate.connection.username", "root");
properties.put("hibernate.connection.password" ,"root");
properties.put("hibernate.connection.driver_class","com.mysql.jdbc.Driver");            
properties.put("hibernate.connection.url", "jdbc:mysql://localhost:3306/"+dbName );
properties.put("hibernate.dialect" ,"org.hibernate.dialect.MySQL5Dialect");
    properties.put("hibernate.hbm2ddl.auto", "");
    properties.put("hibernate.show_sql", "false");
    properties.put("hibernate.format_sql", "false");
    properties.put("hibernate.c3p0.min_size", "5");
    properties.put("hibernate.c3p0.max_size", "10");
    properties.put("hibernate.c3p0.max_statements", "100");
    properties.put("hibernate.c3p0.acquire_increment", "100");
    properties.put("hibernate.c3p0.timeout", "300"); // 5mins
    properties.put("hibernate.c3p0.idle_test_period", "100");
  return properties;

}

当我在调试模式下启动应用程序时,我将分析为 . 我有一个master数据库,并将数据库的名称传递给entityManagerFactory(String dbName)并获得了entityManager并成功读取了master数据库表中的数据库名称,同样也为我们成功创建了这些数据库的实体管理器 . 之后我收到了这个错误:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: At least one JPA metamodel must be present!
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1566)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBea

任何人都可以帮助我如何解决这个问题 .