Announcement Announcement Module
Collapse
No announcement yet.
PersistenceUnitPostProcessor to add JPA annotated classes Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • PersistenceUnitPostProcessor to add JPA annotated classes

    Hello everybody,

    I am working on a project which dynamically has to define what the mapped classes are used in a JPA/Hibernate environment.

    For that i need a fully dynamically configuration. After a lot of research i came up with the following:

    My persistence.xml file:
    Code:
    <persistence xmlns="http://java.sun.com/xml/ns/persistence"
    	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:schemaLocation="http://java.sun.com/xml/ns/persistence 
                         http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
    	version="1.0">
    
    	<persistence-unit name="JPAVisualisatie"
    		transaction-type="RESOURCE_LOCAL">
    		<exclude-unlisted-classes />
    	</persistence-unit>
    
    </persistence>
    I don't use a spring-config file since i need to do everything at runtime.

    I need to load an external jar (user-specified) which contains my mapped files, and database configuration. and then create a Spring connection to the database.

    ConnectionCreator.java
    Code:
    public EntityManagerFactoryCreater(File objectmodel, String jdbcDriver,
    			String pass, String user, String databaseLocation) {
      //add jar to Classpath
      //create String list of classnames
      annotatedClasses = annotatedClasses(objectmodel.getAbsolutePath());
    
    
    //configure datasource
    		ComboPooledDataSource dataSource = new ComboPooledDataSource();
    		dataSource.setJdbcUrl(databaseLocation);
    		try {
    			dataSource.setDriverClass(jdbcDriver);
    		} catch (PropertyVetoException e1) {
    			// TODO Auto-generated catch block
    			e1.printStackTrace();
    		}
    		dataSource.setUser(user);
    		dataSource.setPassword(pass);
    		log.debug("dataSource created");
    
    		log.debug("Create JPA Vendor adapter");
    		HibernateJpaVendorAdapter hjva = new HibernateJpaVendorAdapter();
    		hjva.setGenerateDdl(true);
    		hjva.setShowSql(true);
    		log.debug("JPA Vendor adapter created");
    
    		LocalContainerEntityManagerFactoryBean lcemfb = new LocalContainerEntityManagerFactoryBean();
    		log.debug("lcemfb created");
    		lcemfb.setDataSource(dataSource);
    		lcemfb.setJpaVendorAdapter(hjva);
    		lcemfb.setPersistenceUnitName("JPAVisualisatie");
    		PersistenceUnitPostProcessor pupp = new MyPersistenceUnitPostProcessor(
    				annotatedClasses);
    		PersistenceUnitPostProcessor[] pupptable = { pupp };
    		lcemfb.setPersistenceUnitPostProcessors(pupptable);
    		lcemfb.afterPropertiesSet();
    		log.debug("lcemfb afterpropertiesset aangeroepen");
    
    		JpaTransactionManager transactionManager = new JpaTransactionManager();
    		transactionManager.setEntityManagerFactory(lcemfb.getObject());
    		transactionManager.setDataSource(dataSource);
    		transactionManager.afterPropertiesSet();
    
    		ObjectsDAO dao = new ObjectsDAO();
    		log.debug("dao created");
    		dao.setEntityManagerFactory(lcemfb.getObject());
    		log.debug("dao factory set");
    		try {
    			List<Object> result = dao.getObjects(Class.forName(annotatedClasses
    					.get(0)));
    			for (Object o : result) {
    				log.debug(o);
    			}
    		} catch (ClassNotFoundException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    
    	}
    The postprocessor to add the classes
    Code:
    package be.hogent.iii.caribou.JPAVisualisatie.database;
    
    import java.util.List;
    
    import org.springframework.orm.jpa.persistenceunit.MutablePersistenceUnitInfo;
    import org.springframework.orm.jpa.persistenceunit.PersistenceUnitPostProcessor;
    
    public class MyPersistenceUnitPostProcessor implements
    		PersistenceUnitPostProcessor {
    
    	private final List<String> annotatedClasses;
    
    	public MyPersistenceUnitPostProcessor(List<String> annotatedClasses) {
    		this.annotatedClasses = annotatedClasses;
    	}
    
    	@Override
    	public void postProcessPersistenceUnitInfo(MutablePersistenceUnitInfo pui) {
    		for (String s : annotatedClasses) {
    			pui.addManagedClassName(s);
    		}
    		pui.setExcludeUnlistedClasses(true);
    		pui.setPersistenceUnitName("JPAVisualisatie");
    		pui.addProperty("hibernate.hbm2ddl.auto", "create, drop");
    	}
    }
    Extra: the DAO
    Code:
    package be.hogent.iii.caribou.JPAVisualisatie.database;
    
    import java.util.List;
    
    import org.apache.log4j.Logger;
    import org.springframework.orm.jpa.support.JpaDaoSupport;
    
    /**
     * Klasse die de functies van de interface implementeert. Om zo objecten op te
     * vragen.
     * 
     * @author Caribou
     * 
     */
    public class ObjectsDAO extends JpaDaoSupport implements ObjectsService {
    
    	private final Logger log = Logger.getLogger("ObjectsDAO");
    
    	public List<Object> getObjects(Class<?> klasse) {
    		log.debug("Zoek alle objecten van: " + klasse.getName());
    		return this.getJpaTemplate().find(
    				"select e from " + klasse.getName() + " e");
    
    	}
    
    }

  • #2
    And the output: which just stops, without any error

    Code:
    15:24:57,054  INFO ConnectListener:32 - C:\Users\Caribou\Desktop\model.jar
    15:24:57,057  INFO ConnectListener:33 - com.mysql.jdbc.Driver
    15:24:57,060  INFO ConnectListener:34 - 
    15:24:57,063  INFO ConnectListener:35 - 
    15:24:57,068  INFO ConnectListener:36 - jdbc:mysql://localhost:3306/test
    15:24:57,093 DEBUG CreateEntityManagerFactory:127 - Class found: be.hogent.iii.caribouvisualisation.objectmodel.Hui
    sdier
    15:24:57,097 DEBUG CreateEntityManagerFactory:127 - Class found: be.hogent.iii.caribouvisualisation.objectmodel.Hui
    s
    15:24:57,105 DEBUG CreateEntityManagerFactory:127 - Class found: be.hogent.iii.caribouvisualisation.objectmodel.Per
    soon
    15:24:57,110 DEBUG CreateEntityManagerFactory:127 - Class found: be.hogent.iii.caribouvisualisation.objectmodel.Die
    r
    15:24:57,114 DEBUG CreateEntityManagerFactory:47 - Jar Visited and Filtered
    15:24:57,118 DEBUG CreateEntityManagerFactory:49 - Create datasource
    
    15:24:57,829 DEBUG CreateEntityManagerFactory:60 - dataSource created
    15:24:57,831 DEBUG CreateEntityManagerFactory:62 - Create JPA Vendor adapter
    15:24:57,858 DEBUG CreateEntityManagerFactory:66 - JPA Vendor adapter created
    15:24:57,896 DEBUG CreateEntityManagerFactory:69 - lcemfb created
    ...
    15:24:57,962  INFO LocalContainerEntityManagerFactoryBean:221 - Building JPA container EntityManagerFactory for per
    sistence unit 'JPAVisualisatie'
    15:24:58,080  INFO Version:15 - Hibernate Annotations 3.4.0.GA
    15:24:58,114  INFO Environment:514 - Hibernate 3.2.6
    15:24:58,131  INFO Environment:547 - hibernate.properties not found
    15:24:58,147  INFO Environment:681 - Bytecode provider name : cglib
    ...
    
            Transaction type: RESOURCE_LOCAL
            PU root URL: file:/D:/eclipseworkspace/JPAVisualisatie/target/classes/
            Jar files URLs []
            Managed classes names [
                    be.hogent.iii.caribouvisualisation.objectmodel.Huisdier
                    be.hogent.iii.caribouvisualisation.objectmodel.Huis
                    be.hogent.iii.caribouvisualisation.objectmodel.Persoon
                    be.hogent.iii.caribouvisualisation.objectmodel.Dier]
            Mapping files names []
            Properties [
                    hibernate.hbm2ddl.auto: create, drop]
    15:24:58,739 DEBUG Ejb3Configuration:562 - Detect class: true; detect hbm: true
    15:24:58,761 DEBUG AbstractJarVisitor:116 - Searching mapped entities in jar/par: file:/D:/eclipseworkspace/JPAVisu
    alisatie/target/classes/
    
    15:24:58,779 DEBUG AbstractJarVisitor:162 - Filtering: be.hogent.iii.caribou.JPAVisualisatie.database.EntityManager
    FactoryCreater
    15:24:58,785 DEBUG AbstractJarVisitor:162 - Filtering: be.hogent.iii.caribou.JPAVisualisatie.database.MyPersistence
    UnitPostProcessor
    15:24:58,791 DEBUG AbstractJarVisitor:162 - Filtering: be.hogent.iii.caribou.JPAVisualisatie.database.ObjectsDAO
    15:24:58,949 DEBUG AbstractJarVisitor:162 - Filtering: be.hogent.iii.caribou.JPAVisualisatie.MainClass
    15:24:59,051 DEBUG AnnotationConfiguration:258 - Execute first pass mapping processing
    15:24:59,196 DEBUG AnnotationConfiguration:529 - Process hbm files
    15:24:59,198 DEBUG AnnotationConfiguration:537 - Process annotated classes
    ...
    15:24:59,238  INFO AnnotationConfiguration:369 - Hibernate Validator not found: ignoring
    15:24:59,266 DEBUG NamingHelper:30 - No JNDI name configured for binding Ejb3Configuration
    15:24:59,272 DEBUG AnnotationConfiguration:806 - Validator not present in classpath, ignoring event listener regist
    ration
    15:24:59,282 DEBUG HibernateSearchEventListenerRegister:209 - Search not present in classpath, ignoring event liste
    ner registration.
    15:24:59,290  INFO HibernateSearchEventListenerRegister:53 - Unable to find org.hibernate.search.event.FullTextInde
    xEventListener on the classpath. Hibernate Search is not enabled.
    15:24:59,296 DEBUG Configuration:1291 - Preparing to build session factory with filters : {}
    15:24:59,299 DEBUG AnnotationConfiguration:258 - Execute first pass mapping processing
    15:24:59,302 DEBUG AnnotationConfiguration:529 - Process hbm files
    15:24:59,310 DEBUG AnnotationConfiguration:537 - Process annotated classes
    ...
    15:24:59,346  INFO ConnectionProviderFactory:72 - Initializing connection provider: org.hibernate.ejb.connection.In
    jectedDataSourceConnectionProvider
    15:24:59,360  INFO InjectedDataSourceConnectionProvider:37 - Using provided datasource
    15:24:59,364 DEBUG BasicResourcePool:538 - acquire test -- pool size: 0; target_pool_size: 3; desired target? 1
    ...
    15:24:59,964 TRACE SQLExceptionConverterFactory:52 - Using dialect defined converter
    15:24:59,981  INFO SettingsFactory:283 - Echoing all SQL to stdout
    15:24:59,983  INFO SettingsFactory:290 - Statistics: disabled
    15:24:59,987  INFO SettingsFactory:294 - Deleted entity synthetic identifier rollback: disabled
    15:24:59,992  INFO SettingsFactory:309 - Default entity-mode: pojo
    15:24:59,998  INFO SettingsFactory:313 - Named query checking : enabled
    15:25:00,069  INFO SessionFactoryImpl:161 - building session factory
    15:25:00,074 DEBUG SessionFactoryImpl:173 - Session factory constructed with filter configurations : {}
    15:25:00,077 DEBUG SessionFactoryImpl:177 - instantiating session factory with properties: 
    15:25:00,178 DEBUG SessionFactoryObjectFactory:39 - initializing class SessionFactoryObjectFactory
    15:25:00,185 DEBUG SessionFactoryObjectFactory:76 - registered: 4028907e21590be30121590be48e0000 (unnamed)
    15:25:00,193  INFO SessionFactoryObjectFactory:82 - Not binding factory to JNDI, no JNDI name configured
    15:25:00,201 DEBUG SessionFactoryImpl:308 - instantiated session factory
    15:25:00,211  INFO SchemaUpdate:115 - Running hbm2ddl schema update
    15:25:00,215  INFO SchemaUpdate:126 - fetching database metadata
    15:25:00,222 DEBUG BasicResourcePool:1644 - trace com.mchange.v2.resourcepool.BasicResourcePool@83b00f [managed: 3,
     unused: 2, excluded: 0] (e.g. com.mchange.v2.c3p0.impl.NewPooledConnection@140b8fd)
    15:25:00,243  INFO SchemaUpdate:138 - updating schema
    15:25:00,248 DEBUG AnnotationConfiguration:258 - Execute first pass 
    ...
    15:25:00,293  INFO SchemaUpdate:160 - schema update complete
    15:25:00,302 DEBUG BasicResourcePool:1644 - trace com.mchange.v2.resourcepool.BasicResourcePool@83b00f [managed: 3,
     unused: 2, excluded: 0] (e.g. com.mchange.v2.c3p0.impl.NewPooledConnection@140b8fd)
    15:25:00,307 DEBUG SessionFactoryImpl:392 - Checking 0 named HQL queries
    15:25:00,314 DEBUG SessionFactoryImpl:412 - Checking 0 named SQL queries
    15:25:00,344 DEBUG CreateEntityManagerFactory:78 - lcemfb afterpropertiesset aangeroepen
    15:25:00,377 DEBUG CreateEntityManagerFactory:86 - dao created
    15:25:00,391 DEBUG CreateEntityManagerFactory:88 - dao factory set
    15:25:00,394 DEBUG ObjectsDAO:20 - Zoek alle objecten van: be.hogent.iii.caribouvisualisation.objectmodel.Huisdier
    15:25:00,428 DEBUG JpaTemplate:176 - Creating new EntityManager for JpaTemplate execution
    15:25:00,637 DEBUG SessionImpl:220 - opened session at timestamp: 12427395005
    15:25:00,651 TRACE QueryPlanCache:70 - unable to locate HQL query plan in cache; generating (select e from be.hogen
    t.iii.caribouvisualisation.objectmodel.Huisdier e)
    15:25:00,669  WARN QuerySplitter:116 - no persistent classes found for query class: select e from be.hogent.iii.car
    ibouvisualisation.objectmodel.Huisdier e
    15:25:00,692 TRACE QueryPlanCache:76 - located HQL query plan in cache (select e from be.hogent.iii.caribouvisualis
    ation.objectmodel.Huisdier e)
    15:25:00,702 TRACE HQLQueryPlan:150 - find: select e from be.hogent.iii.caribouvisualisation.objectmodel.Huisdier e
    
    15:25:00,713 TRACE QueryParameters:277 - named parameters: {}
    15:25:00,721 TRACE JDBCContext:237 - after autocommit
    15:25:00,726 DEBUG ConnectionManager:404 - aggressively releasing JDBC connection
    15:25:00,735 TRACE SessionImpl:422 - after transaction completion
    15:25:00,747 DEBUG JpaTemplate:193 - Closing new EntityManager after JPA template execution
    15:25:00,750 DEBUG EntityManagerFactoryUtils:313 - Closing JPA EntityManager
    15:25:00,754 TRACE SessionImpl:273 - closing session
    15:25:00,758 TRACE ConnectionManager:375 - connection already null in cleanup : no action
    Hope anybody can help, i'm stuck on this for more than a week.

    Comment

    Working...
    X