Using hibernate.cfg.xml and JBoss managed datasource - java

I have a project using JBoss + hibernate, and NOT JPA (don't ask me why, just assume this way). So we're using hibernate.cfg.xml and hibernate Session. Well, I'm trying to make JBoss to handle my session, so I changed my hibernate.cfg.xml to something like this:
<hibernate-configuration>
<session-factory name="unitName">
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">false</property>
<property name="hibernate.connection.datasource">MyDS</property>
</session-factory>
</hibernate-configuration>
And in my code I just added:
#PersistenceContext(unitName="unitName") protected Session session;
But when I run the application, it goes:
Caused by: java.lang.IllegalArgumentException: Can't find a persistence unit named 'unitName' in ...
Tried changing from hibernate.cfg.xml to persistence.xml, but still using Session, and I got an error similar to this: https://issues.jboss.org/browse/JBAS-8815
I know, there is a workaround for this error, but my main question is: Can I use a managed Datasource with plain Hibernate/Session and hibernate.cfg.xml? What I'm doing wrong?
Thanks!

Related

Weblogic and hibernate configuration

I need to migrate a project that uses hibernate from Jboss to weblogic. Currently I'm using this configuration:
persistence.xml
<persistence-unit name="pagosHibernate" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>...</class>
<properties>
<property name="hibernate.ejb.cfgfile" value="META-INF/hibernate.cfg.xml"/>
</properties>
</persistence-unit>
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="connection.datasource">MyDS</property>
<property name="jndi.class">weblogic.jndi.WLInitialContextFactory</property>
<property name="hibernate.transaction.manager_lookup_class">org.hibernate.transaction.WeblogicTransactionManagerLookup</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="transaction.factory_class">org.hibernate.transaction.JTATransactionFactory</property>
</session-factory>
</hibernate-configuration>
And the code is:
EntityManager em = this.factory.createEntityManager();
EntityTransaction entityTransaction = em.getTransaction();
entityTransaction.begin();
...
em.persist(device);
entityTransaction.commit();
But I'm getting:
java.sql.SQLException: Cannot call commit when using distributed transactions
Thanks
The DataSource "MyDS" used in Hibernate configuration looks like a XA DataSource.
In your case, Non-XA DataSource should be used. While configuring DataSource in Weblogic, you have to choose appropriate thin driver. Hope this helps.
The problem was caused by the XA datasource as R Sawant said. Nevertheless the solution was creating a non-XA datasource and disabling global transactions (keeping global transactions activated persisted the problem).
I would like to know how to configure this project to work on XA databases but that would be another question.

Hibernate - MySQL - Connection to DB

I'm trying to connect to a MySQL database using Hibernate 3.6.10 with NetBeans 7.4, but when I try to create a new "Hibernate Mapping Wizard" I reply this error message:
Unable to connect: Cannot establish a connection jdbc:mysql://localhost:3306/mydbname using apache.org.derby.jdbc.ClientDriver(Unable to find a suitable driver)
This is my "hibernate.cfg.xml" file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/database</property>
<property name="hibernate.connection.username">username</property>
<property name="hibernate.connection.password">password</property>
</session-factory>
</hibernate-configuration>
I've found another similar problem here: Hibernate - Cannot connect to DB but I still not understand what's wrong.
Best regards.
Andrea
I have never used Hibernate Mapping Wizard but as far as I know this is useful to create a hibernate mapping file with an extension .hbm.xml: see this link as reference.
So the result is a .hbm.xml file that is the mapping of your class to your table.
The point is the in your hibernate.cfg.xml there is no explicit reference to this .hbm.xml file.
Try to add:
<mapping resource="<your_generated_file>.hbm.xml"/>
in your hibernate.cfg.xml and be sure to give all the data needed when using the Hibernate Mapping Wizard tool.
Hope this will be useful!
Ciao!
Nambari and Paolo,
I had to put my config.prop's and mysql driver's "Path" library into CLASSPATH variable. Now it works.
Thankyou all!
Ciao Paolo, grazie!

Hibernate NoCacheRegionFactoryAvailableException

I'm getting a bizarre Hibernate exception that I can't explain. It's telling me that I'm using 2nd level cache, but no where in hibernate.cfg.xml do I specify a 2nd level cache. Here's the exception:
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 class name to property
hibernate.cache.region.factory_class (and make sure the second level cache provider,
hibernate-infinispan, for example, is available in the classpath).
at org.hibernate.cache.internal.NoCachingRegionFactory.buildEntityRegion(NoCachingRegionFactory.java:69)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:348)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1769)
at net.me.myapp.common.dao.SessionFactoryProvider.newSessionFactory(SessionFactoryProvider.java:37)
at net.me.myapp.common.dao.BaseDAO.doPersist(BaseDAO.java:28)
at net.me.myapp.common.dao.WordDAO.deleteAllWords(WordDAO.java:36)
at net.me.myapp.tools.dmapper.DictionaryMapper.run(DictionaryMapper.java:88)
at net.me.myapp.tools.dmapper.DictionaryMapper.main(DictionaryMapper.java:56)
And my hibernate.cfg.xml:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- DataSource & Connection info. -->
<property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>
<property name="hibernate.connection.driver.class">org.h2.Driver</property>
<property name="hibernate.connection.url">jdbc:h2:file:/${MYAPP_HOME}/data/myapp</property>
<property name="hibernate.connection.username">myapp</property>
<property name="hibernate.connection.password">mypassword</property>
<property name="hibernate.connection.pool_size">1</property>
<!-- General Hibernate settings. -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="use_sql_comments">true</property>
<!-- DDL Mode. -->
<property name="hbm2ddl.auto">validate</property>
<!-- All our Hibernate mapping XML files. -->
<mapping class="net.me.myapp.common.dto.WordDTO" />
</session-factory>
</hibernate-configuration>
Any ideas what would be triggering this exception? Thanks in advance!
Pau wrote on hibernate.cache.region.factory_class Required in hibernate.cfg.xml:
The exception is quite self-explanatory. You have to set the
hibernate.cache.region.factory_class property. For instance with ehcache would be adding the following line:
<property name="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheRegionFactory</property>
Using the following line fixed it :
<beans:entry key="hibernate.cache.use_second_level_cache" value="false"/>
But the Hibernate message is probably a warning that we should use second level cache?
I also received this error and took me a while to track down. At one point we were going to have multiple cache regions, but in the end decided we were just going to have one cache pool.
When we merged that change into an older branch - we still had an entity with the old strategy of a cache pool per entity:
#Entity
#Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="tableRegion")
#Table(name = "table")
public class table {
By removing the Cache annotation - it resolved the org.hibernate.cache.NoCacheRegionFactoryAvailableException:
#Entity
#Table(name = "table")
public class table {
Figured I'd post in case anyone else had a similar situation
This error is very misleading, I spent almost a day to finally figure out the root cause. Thought my hibernate config file has defined second level cache and factory class, it was giving me error that hibernate.cache.region.factory_class is not given.
I see that by hibernate.cfg.xml file is also available in classpath. But even after any change in that there was no impact and getting same error.
Finally I realized that for test purpose I have overridden persistence.xml file which has below missing properties under persistence-unit. After adding that issue was resolved.
<properties>
<property name="hibernate.ejb.cfgfile" value="hibernate.cfg.xml" />
</properties>
So this means my application was not able to find hibernate.cfg.xml file and somehow instead of giving error related to missing configuration, it cries out for factory class.
These are the property you need to add to enable second level cache
<!-- Provider for second level cache -->
<property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>

unable to connect to Mongodb using HibernateOGM

I want to use HibernateOGM to interact with MongoDB. I have an cfg.xml file like this:
<hibernate-configuration>
<session-factory>
<property name="hibernate.transaction.factory_class">org.transaction.JDBCTransactionFactory</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.ogm.datastore.provider">mongodb</property>
<property name="hibernate.ogm.datastore.grid_dialect">org.hibernate.ogm.dialect.MongoDBDialect</property>
<property name="hibernate.ogm.mongodb.database">rcfdb</property>
<property name="hibernate.ogm.mongodb.host">127.0.0.1</property>
<property name="hibernate.ogm.mongodb.port">27017</property>
<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<mapping resource="hibernate-contact.hbm.xml"/>
</session-factory>
</hibernate-configuration>
I have also wrote my POJO class, and in the main class I want to populate the database in the mongodb with this code, but I am not able to do this job and I get these line of Infos, how can I solve that:
Session session=null;
OgmConfiguration cfgogm=new OgmConfiguration();
SessionFactory sessionfactory= cfgogm.buildSessionFactory();
session=sessionfactory.openSession();
session.beginTransaction();
System.out.println("Populating the database...");
Contact cnt=new Contact();
cnt.setFirstname("Blabla");
cnt.setLastname("Blabla");
cnt.setEmail("blabla");
session.save(cnt);
session.getTransaction().commit();
System.out.println("Done... :)");
I have no output with this code, and also no exceptions
INFO Lines:
This is the structure of my project:
You have specified MongoDBDialect in the configuration file. But on the console log, you are getting NoopDialect on HHH000400.
And in the next line, you are getting connection was null.
And the last line is, Unable to create requested service.
hibernate.ogm.mongodb.port -> hibernate.ogm.datastore.port
I puzzled over this for two days

Derby database don't save entity after application running

I'm using Embedded Derby DB with hibernate. I'm saving some entities to database. After shutting down the application there is no entities in DB. Why it could be so?
Below my Hibernate configuration
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="dialect">org.hibernate.dialect.DerbyDialect</property>
<property name="connection.driver_class">org.apache.derby.jdbc.EmbeddedDriver</property>
<property name="connection.url">jdbc:derby:\bases\localbase;create=true</property>
<property name="connection.username"></property>
<property name="connection.password"></property>
<property name="hibernate.hbm2ddl.auto">validate</property>
<mapping class="com.example.model.HistoryItem"/>
<mapping class="com.example.model.User"/>
<mapping class="com.example.model.BaseAbstractEntity"/>
</session-factory>
</hibernate-configuration>
This is weird because Derby sync to the disk after each commit by default (unless you set the property derby.system.durability=test). And your url looks correct (although I would use forward slashes).
This begs the question: how do you managed transactions? Are you sure that you are committing them?
Derby likes to hang on to the data - ie keep it in memory. If you try shutting it down by trying something like:
DriverManager.getConnection("jdbc:derby:;shutdown=true");
This should make sure the data is flushed to the disk and derby is shut down cleanly.
At the moment I am trying to get Hibernate 3.6 to do this for me - no luck so far.
Perhaps you are looking in the wrong place. Perhaps the Hibernate application is creating a Derby database in one location on your hard disk, but when you look for the database contents later, you are looking in a different location on your hard disk. Since your Derby URL says "create=true", Derby will quietly create a new empty database for you if you don't get exactly the same location specification as in your original app.

Categories