I'm having trouble using the new multi tenant feature of hibernate 4.1.3
I'm using Glassfish 3.1 with JPA2 and Hibernate 4.1.3 as provider.
This is my persistence.xml
<persistence version="2.0" 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_2_0.xsd">
<persistence-unit name="AuroraServicePU" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/sqlserver/Aurora</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="hibernate.show_sql" value="false"/>
<property name="hibernate.default_batch_fetch_size" value="100"/>
<property name="hibernate.cache.use_second_level_cache" value="false"/>
<property name="hibernate.cache.use_query_cache" value="false"/>
<property name="hibernate.tenant_identifier_resolver" value="org.dna.aurora.web.TenantResolver" />
<property name="hibernate.multiTenancy" value="DISCRIMINATOR" />
</properties>
</persistence-unit>
</persistence>
This is the exception I get when try to deploy the application.
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final} INFO:
HHH000412: Hibernate Core {4.1.3.Final} INFO: HHH000206:
hibernate.properties not found INFO: HHH000021: Bytecode provider name
: javassist INFO: HHH000204: Processing PersistenceUnitInfo [ name:
AuroraServicePU ...] SEVERE: Exception while invoking class
org.glassfish.persistence.jpa.JPADeployer prepare method SEVERE:
Exception while preparing the app SEVERE: The log message is null.
java.lang.NullPointerException at
org.hibernate.engine.jdbc.internal.JdbcServicesImpl$MultiTenantConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcServicesImpl.java:260)
at
org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:117)
at
org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:75)
at
org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:159)
at
org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:131)
at
org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:71)
at
org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2277)
at
org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2273)
at
org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1742)
at
org.hibernate.ejb.EntityManagerFactoryImpl.(EntityManagerFactoryImpl.java:76)
at
org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:905)
at
org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:890)
at
org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:73)
at
org.glassfish.persistence.jpa.PersistenceUnitLoader.loadPU(PersistenceUnitLoader.java:205)
at
org.glassfish.persistence.jpa.PersistenceUnitLoader.(PersistenceUnitLoader.java:119)
at
org.glassfish.persistence.jpa.JPADeployer$1.visitPUD(JPADeployer.java:213)
at
org.glassfish.persistence.jpa.JPADeployer$PersistenceUnitDescriptorIterator.iteratePUDs(JPADeployer.java:486)
at
org.glassfish.persistence.jpa.JPADeployer.createEMFs(JPADeployer.java:220)
at
org.glassfish.persistence.jpa.JPADeployer.prepare(JPADeployer.java:166)
at
com.sun.enterprise.v3.server.ApplicationLifecycle.prepareModule(ApplicationLifecycle.java:870)
at
com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:410)
at
com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:240)
at
org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:370)
at
com.sun.enterprise.v3.admin.CommandRunnerImpl$1.execute(CommandRunnerImpl.java:355)
at
com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:370)
at
com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1067)
at
com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1200(CommandRunnerImpl.java:96)
at
com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1247)
at
com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1235)
at
com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:465)
at
com.sun.enterprise.v3.admin.AdminAdapter.service(AdminAdapter.java:222)
at
com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:168)
at
com.sun.enterprise.v3.server.HK2Dispatcher.dispath(HK2Dispatcher.java:117)
at
com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:234)
at
com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:822)
at
com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:719)
at
com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1013)
at
com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
at
com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at
com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at
com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at
com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at
com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at
com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71) at
com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at
com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:619)
SEVERE: Exception while preparing the app
UPDATE:
I've read the docs again and notice this important peace of information:
DISCRIMINATOR Correlates to the partitioned (discriminator) approach.
It is an error to attempt to open a session without a tenant
identifier using this strategy. This strategy is not yet implemented
in Hibernate as of 4.0 and 4.1. Its support is planned for 5.0.
Is that really means the discriminator strategy is not available right now?
Maybe this is the whole problem?
Any help will be great.
Thank you,
Ido.
You have not specified how Hibernate should obtain connections. Did you read the docs related to this? http://docs.jboss.org/hibernate/orm/4.1/devguide/en-US/html_single/#d5e4583
And specifically:
http://docs.jboss.org/hibernate/orm/4.1/devguide/en-US/html_single/#d5e4658
http://docs.jboss.org/hibernate/orm/4.1/devguide/en-US/html_single/#d5e4702
Related
I have a web application which is written in JEE. I am using hibernate as a JPA provider and I would like to use Infinispan as a second level cache. As I went through internet I noticed that only adding several lines is needed. I added in my persistence.xml these lines
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.infinispan.InfinispanRegionFactory"/>
<property name="javax.persistence.sharedCache.mode" value="ENABLE_SELECTIVE"/>
<property name="hibernate.cache.use_second_level_cache" value="true"/>
<property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.infinispan.InfinispanRegionFactory"/>
<property name="hibernate.cache.use_query_cache" value="true"/>
but during deploying ear and war file on JBoss I receive an error message
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.spi.CacheImplementor]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:244)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:208)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:242)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879)
... 83 more
Caused by: org.hibernate.cache.CacheException: Unable to start region factory
at org.hibernate.cache.infinispan.InfinispanRegionFactory.start(InfinispanRegionFactory.java:415)
at org.hibernate.internal.CacheImpl.<init>(CacheImpl.java:49)
at org.hibernate.engine.spi.CacheInitiator.initiateService(CacheInitiator.java:28)
at org.hibernate.engine.spi.CacheInitiator.initiateService(CacheInitiator.java:20)
at org.hibernate.service.internal.SessionFactoryServiceRegistryImpl.initiateService(SessionFactoryServiceRegistryImpl.java:46)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:234)
... 88 more
Caused by: org.infinispan.jmx.JmxDomainConflictException: ISPN000034: There's already a JMX MBean instance type=CacheManager,name="SampleCacheManager" already registered under 'org.infinispan' JMX domain. If you want to allow multiple instances configured with same JMX domain enable 'allowDuplicateDomains' attribute in 'globalJmxStatistics' config element
at org.infinispan.jmx.JmxUtil.buildJmxDomain(JmxUtil.java:52)
at org.infinispan.jmx.CacheManagerJmxRegistration.updateDomain(CacheManagerJmxRegistration.java:79)
at org.infinispan.jmx.CacheManagerJmxRegistration.buildRegistrar(CacheManagerJmxRegistration.java:73)
at org.infinispan.jmx.AbstractJmxRegistration.registerMBeans(AbstractJmxRegistration.java:37)
at org.infinispan.jmx.CacheManagerJmxRegistration.start(CacheManagerJmxRegistration.java:41)
at org.infinispan.manager.DefaultCacheManager.start(DefaultCacheManager.java:639)
at org.infinispan.manager.DefaultCacheManager.<init>(DefaultCacheManager.java:300)
at org.hibernate.cache.infinispan.InfinispanRegionFactory.createCacheManager(InfinispanRegionFactory.java:532)
at org.hibernate.cache.infinispan.InfinispanRegionFactory$1.doWork(InfinispanRegionFactory.java:500)
at org.hibernate.cache.infinispan.InfinispanRegionFactory$1.doWork(InfinispanRegionFactory.java:473)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.workWithClassLoader(ClassLoaderServiceImpl.java:342)
at org.hibernate.cache.infinispan.InfinispanRegionFactory.createCacheManager(InfinispanRegionFactory.java:472)
at org.hibernate.cache.infinispan.InfinispanRegionFactory.start(InfinispanRegionFactory.java:380)
... 93 more
UPDATE
When my persistence unit looks like this
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="myPersistenceUnit" transaction-type="RESOURCE_LOCAL">
<non-jta-data-source>java:jboss/datasources/myDatasource</non-jta-data-source>
<mapping-file>META-INF/orm_mapping.xml</mapping-file>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
...
<properties>
...
<property name="hibernate.cache.use_second_level_cache" value="true" />
...
</properties>
</persistence-unit>
</persistence>
I am getting an exception
Caused by: org.hibernate.cache.NoCacheRegionFactoryAvailableException: Second-level cache is used in the application, but property hibernate.cache.region.factory_class is not given; please either disable second level cache or set correct region factory using the hibernate.cache.region.factory_class setting and make sure the second level cache provider (hibernate-infinispan, e.g.) is available on the classpath.
at org.hibernate.cache.internal.NoCachingRegionFactory.buildEntityRegion(NoCachingRegionFactory.java:66)
at org.hibernate.internal.SessionFactoryImpl.determineEntityRegionAccessStrategy(SessionFactoryImpl.java:619)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:332)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879)
... 83 more
After adding below line to persistence.xml
<property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.infinispan.InfinispanRegionFactory" />
I am still getting exception with JMX MBean
Caused by: org.infinispan.jmx.JmxDomainConflictException: ISPN000034: There's already a JMX MBean instance type=CacheManager,name="SampleCacheManager" already registered under 'org.infinispan' JMX domain. If you want to allow multiple instances configured with same JMX domain enable 'allowDuplicateDomains' attribute in 'globalJmxStatistics' config element
at org.infinispan.jmx.JmxUtil.buildJmxDomain(JmxUtil.java:52)
at org.infinispan.jmx.CacheManagerJmxRegistration.updateDomain(CacheManagerJmxRegistration.java:79)
at org.infinispan.jmx.CacheManagerJmxRegistration.buildRegistrar(CacheManagerJmxRegistration.java:73)
at org.infinispan.jmx.AbstractJmxRegistration.registerMBeans(AbstractJmxRegistration.java:37)
at org.infinispan.jmx.CacheManagerJmxRegistration.start(CacheManagerJmxRegistration.java:41)
at org.infinispan.manager.DefaultCacheManager.start(DefaultCacheManager.java:639)
at org.infinispan.manager.DefaultCacheManager.<init>(DefaultCacheManager.java:300)
at org.hibernate.cache.infinispan.InfinispanRegionFactory.createCacheManager(InfinispanRegionFactory.java:532)
at org.hibernate.cache.infinispan.InfinispanRegionFactory$1.doWork(InfinispanRegionFactory.java:500)
at org.hibernate.cache.infinispan.InfinispanRegionFactory$1.doWork(InfinispanRegionFactory.java:473)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.workWithClassLoader(ClassLoaderServiceImpl.java:342)
at org.hibernate.cache.infinispan.InfinispanRegionFactory.createCacheManager(InfinispanRegionFactory.java:472)
at org.hibernate.cache.infinispan.InfinispanRegionFactory.start(InfinispanRegionFactory.java:380)
... 93 more
Maybe I need some kind of infinispan config file where I will be able to place
<jmx duplicate-domains="true" />
like it is mentioned here Infinispan as second level cache hibernate
You should check the EAP 7 documentation since all the configuration required to get second level cache (powered by Infinispan behind the scenes) is this:
<persistence-unit name="...">
(...) <!-- other configuration -->
<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
<properties>
<property name="hibernate.cache.use_second_level_cache" value="true" />
<property name="hibernate.cache.use_query_cache" value="true" />
</properties>
</persistence-unit>
https://access.redhat.com/documentation/en-us/red_hat_jboss_enterprise_application_platform/7.1/html/development_guide/java_persistence_api_jpa#second_level_caches
The hibernate version should be 5.0.x.
persistence.xml :
<persistence ...>
<persistence-unit ...>
...
<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode> <!-- ADD THIS -->
<properties>
...
<property name="hibernate.cache.use_second_level_cache" value="true" /> <!-- KEEP THIS -->
</properties>
</persistence-unit>
</persistence>
Remove all other hibernate.cache.* properties----leaving only the above
Note that using the above setting you must explicitly mark entities as #Cacheable. It can be used the ALL setting for shared-cache-mode if not wish to explicitly mark each entity as #cacheable---- and then all entities would be cached.
Additional documentation on configuration and implementation may be found in
EAP 7: Hibernate 5 User Guide(http://docs.jboss.org/hibernate/orm/5.0/userguide/html_single/Hibernate_User_Guide.html#caching) and Hibernate 5 Developer Guide(http://docs.jboss.org/hibernate/orm/5.0/devguide/en-US/html_single/#d5e1433) and Infinispan 8 User Guide(http://infinispan.org/docs/8.1.x/user_guide/user_guide.html)
Im trying to configure a simple JPA project and I'm very stuck.
I have a working dataSource (MySQL) & GlassFish with multiple tables.
I did the following steps (all of the files generated by Intellij):
Create new project with Java EE Persistance with Hibernate Provider.
Import DB that has a Student table.
Generate Entity classes with Intellij IDE.
Import Hibernate-entitymanager library from Maven.
Import MySQL connector.
Try to run a simple JPA program to create new row but I get an exeption :
No Persistence provider for EntityManager named persistenceUnit
What can be the problem? I tried almost every tutorial and every question here but with no success!
Please Help me!
(sometimes the Hibernate in the persistance provider is colored red)
persistance:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="NewPersistenceUnit">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>modules.CourseEntity</class>
<class>modules.StuCouEntity</class>
<class>modules.StudentsEntity</class>
<class>modules.TeacherEntity</class>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.connection.password" value="123456"/>
<property name="hibernate.archive.autodetection" value="class"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
Main.java:
import modules.StudentsEntity;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class MainClass
{
public static void main(String[] args)
{
StudentsEntity stu = new StudentsEntity();
stu.setName("David");
EntityManagerFactory emf = Persistence.createEntityManagerFactory("persistenceUnit");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
try
{
em.persist(stu);
em.getTransaction().commit();
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
ex.printStackTrace();
em.getTransaction().rollback();
}
finally
{
em.close();
}
}
}
error:
June 16, 2017 5:47:07 PM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
June 16, 2017 5:47:07 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.1.5.Final}
June 16, 2017 5:47:07 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
June 16, 2017 5:47:07 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named persistenceUnit
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:84)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
at MainClass.main(MainClass.java:17)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
You defined
<persistence-unit name="NewPersistenceUnit">
while tryng to call Persistence.createEntityManagerFactory("persistenceUnit");
change NewPersistenceUnit to persistenceUnit
I have a JavaFX Maven project in IntelliJ, which uses Hibernate. When the app is starting, I am getting the following error message:
No persistence provider for entitymanager named xyz
Why? My META-INF/persistence.xml is located in myproject/src/main/resources (the directory is checked as resource folder in project settings).
I am sure I've downloaded all Hibernate JARs via Maven.
My persistence.xml is correct:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="xyz">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>entity.User</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.SQLiteDialect"/>
<property name="javax.persistence.jdbc.url" value="jdbc:sqlite:java.sqlite"/>
<property name="javax.persistence.jdbc.driver_class" value="oracle.jdbc.driver"/>
<property name="hibernate.hbm2ddl.auto" value="none"/>
<property name="hibernate.show_sql" value="false"/>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
</properties>
</persistence-unit>
</persistence>
Java code:
factory = Persistence.createEntityManagerFactory("xyz");
In my an old non-Maven project the code above worked fine.
your persistence.xml must be located in the META-INF folder
There was a different context and solution in my case:
Context:
see the log below:
org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [org.h2.Driver] at URL [jdbc:h2:tcp://localhost/~/test]
org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=sa}
org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
...
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: javax.persistence.PersistenceException: No Persistence provider for EntityManager named NewPersistenceUnit`
Solution:
As its clear from logs above, persistenceUnit has been found and some data like dialect, username and password is extracted.
There was problem in mapping of entities. By commenting out #Entity one by one on entities, I was able to find the problem and solve it, without any change in persistence.xml file.
I have no idea why error like No Persistence provider for EntityManager named X should be shown when there is a problem in entity mapping!
I have inherited a maven based project that was created with Netbeans 7.4. I have configured a local Glassfish 3.1.2.2 in the servers tab, set up JDBC connection pools and resources and can debug the project correctly.
However, I created 2 more tables in one of the connected databases, and let Netbeans generate 2 new entities from the Database schema. The entities are generated correctly, but when I start using them and start a debug session on the glassfish server I can see error messages being logged saying that the entities are not declared in the persistence unit.
I am trying to find what persistence.xml is being used, but although I find a lot of old ones inside the project structure (that I didn't create myself and I don't have contact with the authors) I cannot find any that seems to be the one being used. Hibernate only refers to the Persistence Unit name, not to the path of the file being used.
I am new to Java Persistence, so I am a bit confused. Can anybody suggest how I find, or recreate, the persistence.xml file?
EDIT: Here is the stack trace:
INFO: HHH000412: Hibernate Core {4.2.6.Final}
INFO: HHH000206: hibernate.properties not found
INFO: HHH000021: Bytecode provider name : javassist
INFO: HHH000204: Processing PersistenceUnitInfo [
name: core_rw_pu_hibernate
...]
INFO: HHH000130: Instantiating explicit connection provider: org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
SEVERE: Exception while invoking class org.glassfish.persistence.jpa.JPADeployer prepare method
SEVERE: Exception while preparing the app
SEVERE: [PersistenceUnit: core_rw_pu_hibernate] Unable to build EntityManagerFactory
javax.persistence.PersistenceException: [PersistenceUnit: core_rw_pu_hibernate] Unable to build EntityManagerFactory
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:924)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:899)
at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:76)
at org.glassfish.persistence.jpa.PersistenceUnitLoader.loadPU(PersistenceUnitLoader.java:206)
at org.glassfish.persistence.jpa.PersistenceUnitLoader.<init>(PersistenceUnitLoader.java:120)
at org.glassfish.persistence.jpa.JPADeployer$1.visitPUD(JPADeployer.java:224)
at org.glassfish.persistence.jpa.JPADeployer$PersistenceUnitDescriptorIterator.iteratePUDs(JPADeployer.java:495)
at org.glassfish.persistence.jpa.JPADeployer.createEMFs(JPADeployer.java:233)
at org.glassfish.persistence.jpa.JPADeployer.prepare(JPADeployer.java:168)
at com.sun.enterprise.v3.server.ApplicationLifecycle.prepareModule(ApplicationLifecycle.java:871)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:410)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:240)
at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:389)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$1.execute(CommandRunnerImpl.java:348)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:363)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1085)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1200(CommandRunnerImpl.java:95)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1291)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1259)
at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:461)
at com.sun.enterprise.v3.admin.AdminAdapter.service(AdminAdapter.java:212)
at com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:179)
at com.sun.enterprise.v3.server.HK2Dispatcher.dispath(HK2Dispatcher.java:117)
at com.sun.enterprise.v3.services.impl.ContainerMapper$Hk2DispatcherCallable.call(ContainerMapper.java:354)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:744)
Caused by: org.hibernate.AnnotationException: Use of #OneToMany or #ManyToMany targeting an unmapped class: com.acme.ee.domain.entity.DeviceEntity.deviceInOuts[com.acme.ee.domain.entity.DeviceInOuts]
at org.hibernate.cfg.annotations.CollectionBinder.bindManyToManySecondPass(CollectionBinder.java:1059)
at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:733)
at org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:668)
at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:69)
at org.hibernate.cfg.Configuration.originalSecondPassCompile(Configuration.java:1632)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1390)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1777)
at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:96)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:914)
... 38 more
In a normal maven-based web application project the persistence.xml has to be placed in the folder:
src/main/resources/META-INF
In the NetBeans Projects tab this folder can be seen by opening "Other Sources" (should be right under "Source Packages").
If this isn't the right file, you have the option to search for the name of the PersistenceUnit in the whole project. The name has to be declared in the persistence.xml. If it finds multiple files you can find the one which is actually used by making the files unparsable one by one. To do this, just remove a closing tag (like </provider>) in the first file, save it and deploy it. If it throws an error which tells you the file is unparsable (probably something containing the class SAXParser), this is the file which is used. If it doesn't throw an error, try again with the next file.
To fix the initial problem (new entities not in persistence unit) make sure you add the new entity classes in the persistence.xml like this:
<class>com.company.SomeClass</class>
Another option is to add the following to your persistence.xml:
<exclude-unlisted-classes>false</exclude-unlisted-classes>
This should automatically discover all entities, but sometimes this doesn't work because the project structure doesn't fit, then you have to explicitly list every entity.
your persistence.xml should have information about your connection to the database like bellow:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="YOUR_PERSISTENCE_UNIT_NAME" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/YOUR_JNDI_NAME</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<!--<property name="javax.persistence.schema-generation.database.action" value="none"/> -->
<property name="hibernate.archive.autodetection" value="class"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.SunOneJtaPlatform"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/YOUR_SCHEMA_NAME?zeroDateTimeBehavior=convertToNull"/>
<property name="hibernate.connection.username" value="YOUR_USERNAME"/>
<property name="hibernate.connection.password" value="YOUR_PASSWORD"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
</persistence>
The Spring project (in its production form) will be using a MySQL database. I want the tests ran on the project to use HYPERSONIC_IN_MEMORY.
I've added the following new files in the test/resources folder.
database.properties
applicationContext.xml
test-persistence.xml
However, the project throws a MYSQL syntax error (it's trying to use MySQL with HYPERSONIC somehow).
Considering the fact that I'm a total beginner (first project in Spring), I'd like to know what the steps are to switching databases for testing (what I might be doing wrong).
LE:
This is what I'm getting when running maven tests:
Tests run: 9, Failures: 0, Errors: 9, Skipped: 0, Time elapsed: 12.29 sec <<< FAILURE!
testCountAllAccountAllocations(com.mms.pone.portal.domain.AccountAllocationIntegrationTest) Time elapsed: 11.813 sec <<< ERROR!
org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Cannot open connection
at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:427)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:371)
at org.springframework.test.context.transaction.TransactionalTestExecutionListener$TransactionContext.startTransaction(TransactionalTestExecutionListener.java:513)
at org.springframework.test.context.transaction.TransactionalTestExecutionListener.startNewTransaction(TransactionalTestExecutionListener.java:271)
at org.springframework.test.context.transaction.TransactionalTestExecutionListener.beforeTestMethod(TransactionalTestExecutionListener.java:164)
at org.springframework.test.context.TestContextManager.beforeTestMethod(TestContextManager.java:358)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:172)
at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:104)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:70)
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Cannot open connection
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1387)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1315)
at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:1397)
at org.hibernate.ejb.TransactionImpl.begin(TransactionImpl.java:63)
at org.springframework.orm.jpa.DefaultJpaDialect.beginTransaction(DefaultJpaDialect.java:70)
at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:377)
... 31 more
Caused by: org.hibernate.exception.GenericJDBCException: Cannot open connection
And a lot more of those. I get the feeling that maven isn't using the new xml files and still sticking to the old ones.
Any way I can figure that out?
Search for org.hibernate.dialect.MySQLDialect and replace it with org.hibernate.dialect.HSQLDialect (docs)
[EDIT] The error says "Cannot open connection". Check the JDBC URL, user+password and for more errors further up in the output.
I'm assuming this is how your original applicationContext.xml looked (also assuming that the persistence.xml file defines a persitence unit with jndi name 'testEM')
<jee:jndi-lookup id="entityManagerFactory" jndi-name="java:comp/env/testEM" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
For testing purposes, you basically need to override how entityManagerFactory is created.
In your applicationContext-test.xml file override 'entityManagerFactory' bean definition as shown in the snippet below. Create a 'META-INF/test-persistence.xml' in src/test/resources that creates a connection to hsql in-memory db.
test-persistence.xml
<persistence-unit name="testPu">
<properties>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:mem:schemaname"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
</properties>
</persistence-unit>
applicationContext-test.xml
<!-- Import the original applicationContext and override properties for test purposes -->
<import resource="classpath:applicationContext" />
<!-- In our case, we need to override entityManagerFactory definition -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation" value="classpath*:META-INF/test-persistence.xml" />
<!-- other properties (omitted) -->
</bean>