Hibernate creates EntityManager too slow

Hi guys!
I’m using Hibernate to create EntityManger via the following EntityMangerFactory:

public class JpaEntityManagerFactory {

    private String DB_SERVER;
    private int DB_PORT;
    private String DB_USER_NAME;
    private String DB_PASSWORD;
    private String DB_NAME;
    private Class[] entityClasses;

    public JpaEntityManagerFactory(String databaseName, Class[] entityClasses) {
        try {
            String dbconfigPath = JpaEntityManagerFactory.class.getClassLoader().getResource("config/dbconfig.properties").getFile();
            Properties dbprops = FileIO.loadProperties(dbconfigPath);
            DB_SERVER = dbprops.getProperty("hqspf.simplehost");
            DB_PORT = Integer.parseInt(dbprops.getProperty("hqspf.port"));
            DB_USER_NAME = dbprops.getProperty("hqspf.user");
            DB_PASSWORD = dbprops.getProperty("hqspf.password");
            DB_NAME = databaseName;
            this.entityClasses = entityClasses;
        } catch (IOException ex) {
            Logger.getLogger(JpaEntityManagerFactory.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public EntityManager getEntityManager() {
        return getEntityManagerFactory().createEntityManager();
    }

    protected EntityManagerFactory getEntityManagerFactory() {
        PersistenceUnitInfo persistenceUnitInfo = getPersistenceUnitInfo(getClass().getSimpleName());
        Map<String, Object> configuration = new HashMap<>();
        return new EntityManagerFactoryBuilderImpl(new PersistenceUnitInfoDescriptor(persistenceUnitInfo), configuration)
                .build();
    }

    protected HibernatePersistenceUnitInfo getPersistenceUnitInfo(String name) {
        return new HibernatePersistenceUnitInfo(name, getEntityClassNames(), getProperties());
    }

    protected List<String> getEntityClassNames() {
        return Arrays.asList(getEntities())
                .stream()
                .map(Class::getName)
                .collect(Collectors.toList());
    }

    protected Properties getProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
        properties.put("hibernate.id.new_generator_mappings", true);
        properties.put("hibernate.generate_statistics", true);
        properties.put("hibernate.connection.datasource", getMysqlDataSource());
        return properties;
    }

    protected Class[] getEntities() {
        return entityClasses;
    }

    protected DataSource getMysqlDataSource() {
        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        String DB_URL = "jdbc:mysql://" + DB_SERVER + ":" + DB_PORT + "/" + DB_NAME + "?serverTimezone=UTC&user=" + DB_USER_NAME + "&password=" + DB_PASSWORD;
        mysqlDataSource.setURL(DB_URL);
        mysqlDataSource.setUser(DB_USER_NAME);
        mysqlDataSource.setPassword(DB_PASSWORD);
        return mysqlDataSource;
    }
}

I’m using MySQL as database and my database consists 200 tables with many foreign keys. In the code above, I use PersistenceUnitInfo to define persistent unit, in which I need to pass about 200 entities class names (via array entityClasses). This slows down the performance. It takes about 30 seconds to create an EntityManger. Can any one tell me how to avoid this nightmare?

You are always creating a new EntityManagerFactory which is completely unnecessary. A EntityManagerFactory only has to be created once. You will see, that creating an EntityManager is quite fast when you use an existing EntityManagerFactory

I know that EntityManagerFactory needs to be created once, and try to create one EntityManagerFactory with 200 entities classes passed to constructor above via entityClasses variable. But this slows down the performance. When I try to passed single entity class to constructor and create one EntityManagerFactory for each entity when needed, the application works faster. It is very strange.

The creation of an EntityManagerFactory is an expensive operation as it will check all entities, build a metamodel, create database connections, prepopulate caches etc. Due to that, this should only be done during application initialization. I don’t know how you are using this JpaEntityManagerFactory, but rebuilding it every time you need an EntityManager is wrong.