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?