Dynamically configure an EJB3 EntityManager and its entities.

    In a multi-company, multi-database configuration, it is not desirable to rely on hardcoded, static instances of persistence.xml to specify available EntityManagers.

    You need to be able to start an EntityManagerFactory by pointing it at a javax.sql.DataSource, and telling it the list of annotated clases that it is to manage.

    Here's how to do it:

    //    Configure our EJB3 EntityManagerFactory
        Ejb3Configuration ejbconf = new Ejb3Configuration();
        ejbconf.setProperty("hibernate.connection.datasource", "java:/" + datasourceName);
        ejbconf.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect");
        ejbconf.setProperty("hibernate.show_sql", "false");
        ejbconf.setProperty("hibernate.ejb.naming_strategy", "com.fcl.greenfield.naming.FCLNamingStrategy");
        ejbconf.setProperty("hibernate.hbm2ddl.auto", "update");
    
    //    Find all our persistent classes from persistence.jar
        JarVisitor.Filter[] filters = new JarVisitor.Filter[2];
        filters[0] = new JarVisitor.PackageFilter( false, null ) {
            public boolean accept(String javaElementName) {
                return true;
            }
        };
        filters[1] = new JarVisitor.ClassFilter(
                false, new Class[]{
                Entity.class,
                MappedSuperclass.class,
                Embeddable.class}
        ) {
            public boolean accept(String javaElementName) {
                return true;
            }
        };
    
    //    Add all persistent classes to EJB3 config
        JarVisitor j = JarVisitor.getVisitor(Thread.currentThread().getContextClassLoader().getResource("persistence.jar"), filters);
        Set<JarVisitor.Entry>[] entries = (Set<JarVisitor.Entry>[])j.getMatchingEntries();
        List<String> classes = new ArrayList<String>();
        for (int i = 0; i < entries.length; i++)
        {
            for (JarVisitor.Entry c : entries[i])
            {
                Logger.info("Found entity " + c.getName());
                ejbconf.addAnnotatedClass(Class.forName(c.getName()));
            }
        }
    
        Logger.info("Building SessionFactory");
        EntityManagerFactory emf = ejbconf.createEntityManagerFactory();
        EntityManager em = emf.createEntityManager();