No Persistence provider for EntityManager named Hibernate error

No Persistence provider for EntityManager named

If you are working on hibernate, then there are two ways to provide the configuration to it. Either you would be using hibernate.cfg.xml or persistence.xml

In both cases, hibernate would be using the information like the connection string information and classes associated with tables.

If you are using persistence.xml and you are getting No Persistence provider for EntityManager named error, then there the following would be an issue and here is how you solve those.
Continue reading No Persistence provider for EntityManager named Hibernate error

JSF App slow with JPA connection

If you are working on Java Persistence API JPA on tomcat or any other web server this would be happening if you have multiple threads going off for connections.

The rule of thumb shall be to have one EntityManagerFactory and get EntityManagers out of it. Hence we would have one factory but multiple products that would take care of closing and managing them selves.

What are the signs:

1. Do you instantiate Persistence.createEntityManagerFactory(“name”) from multiple places?
2. What do you see on Process when you run

ps -aux | grep tomcat

Do you see multiple instances

If either or both of the above have yes, then here is the solution.

The first thing have single instance of ManagerFactory


package com.enderase.persistence;

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
* Singlton implementation for EntityManagerFactory
*
* @author Kaleb Woldearegay<kaleb@gullele.com>
*/
public class HibernateUtil {
private static final EntityManagerFactory entityManagerFactory;

static {
try {
entityManagerFactory = Persistence.createEntityManagerFactory("jpa");
} catch (Throwable exception) {
//log your error here
throw new ExceptionInInitializerError(exception);
}
}

public static EntityManagerFactory getEntityManager() {
return entityManagerFactory;
}
}

Then make sure you are taking care of the instances of the EntityManagers that are created from the factory using

EntityManagerFactory entityManagerFactory = HibernateUtil.getEntityManager();
EntityManager em = entityManagerFactory.createEntityManager();

Make sure to close them appropriately after using them

This should pretty much take care of the problem

 

nosuchfielderror tokentypetoastclassmap Error in JPA

Did you come across this error while trying to access Hibernate query language like simple select?
The problem is mainly on the version of the antlr.jar
If you are not using Application server and putting all the jar by your self, check if you have added antlr-build.jar or some earlier version of that jar. Replace it and you should be fine.
Good luck.

An association from the table refers to an unmapped class Hibernate Exception

Got An association from the table

refers to an unmapped class exception while running hibernate on your app?
Here is a solution
Mostly it would be related to the hbm file of the table that it is complaining. On that hbm file, make sure if you have the class attribute on the option properly addressed like if you haven’t added the package on the top, make sure you provide the FQN of the class.

Also make sure if the hbm file is listed on the hibernate.cfg.xml/ where ever the list of the hbm files are listed.

Mostly this would solve the problem.

NonUniqueObjectException: a different object with the same identifier value was already associated with the session

The error different object with the same identifier value was already associated with the session would happen quite sometime while working on hibernate with java web application

It occurs when the hibernate session contains object to be updated and when the application tries to update another object with the same id as that of the session owned one.

Let’s assume there is an object Can with properties material and volume as follows for simple illustration


public class Can{
  private Integer canId;
  private String material;
  private Double volume;
  //getters; setters;
}

Assume we have DAO for this object named CanDao.

So, being on your jsf dataTable you selected one ‘can’ object to be updated or deleted. I just put the CanDao object directly into the Bean for the illustration purpose – it is good to wrap this object in the service object, say CanService, for easier manupulation.

Lets have the bean as follows:


class CanBean{
   private HtmlDataTable canTable; //for binding list of can objects from jsf list
   private CanDao canDao; //dao object;
   private List cans; //list jsf datatable would use it.
   .
   .
   .
   public String update(){
      //get the selected object from data table
      ICan selectedCan = (ICan)this.canTable.getRowData();
      this.canDao.saveOrUpdate(selectdCan);
      return "Update";
   }
}

Here the line calling saveOrUpdate would be responsible for throwing the error of different object with the same identifier value was already associated with the session

Here is how to fix it
Since the session contain the same identifier, let’s get the actual or original object from the session it self


  //corrected update method for Can Bean
   public String update(){
      //get the selected object from data table
      ICan selectedCan = (ICan)this.canTable.getRowData();
      ICan original = this.canDao.getById(selectedCan.getCanId()); //
      original.setVolume(selectedCan.getVolume());      
      original.setMaterial(selectedCan.getMaterial());
      this.canDao.saveOrUpdate(original);
      return "Update";
   }

This would fix the problem. But, there are other ways of preventing the session problem from occurring – googling a bit might help.

If you are J2EE developer:

Hello world with maven step by step

See how you can add session bean

Why do I get can not forward after response error and how to solve it

Bean CurrentlyInCreationException: Error creating bean with name : Requested bean is currently in creation: Is there an unresolvable circular reference?

This CurrentlyInCreationExceptionexception happens during the construction of the bean.

If the bean has reference to other beans, and if those beans which are referenced have the this bean as property or constructor parameter, then it would be cyclic and hence this exception would be thrown.

So, check if you have beans that are referring to each other on you hbm/annotations files.

Could not open Hibernate Session for transaction

This problem happens when the connection to the database is disconnected or was not created at all by the application, but pool assumes connection is established.
Remedy for this could be checking credential to the database [username, password, host, port] and also checking the connection object before proceeding to database tasks like reading or updating.

hibernate automatically saves/edits objects that are updated

Kind of mysterious – all you want to do would be to update the some component on your java logic and it is automatically saved in the database.
Here is the typical scenario, if you are updating collection of objects and and updating one object would also update others based on some logic – say reordering of numbers, the session would all be saved without saving all the collections – yup I got this exact situation and the reason was

After the update, I have another ajax call to the backend where I would get the list of objects. And the method which collect the objects was annotated as Transactional. In this case, all the dirty objects in the session would be saved though what I wanted was to read only.

So, I changed the annotation to Transactional(readOnly=true) – that took care of it.

eraser

deleted object would be re-saved by cascade (remove deleted object from associations):

Kind of oxymoron ha?!.

You try to delete but you are told it would be re-saved.

Actually it is a safe guard by hibernate that this action is meaningless unless you do the actual stuff.

Two things to check:

  • make sure any collection that holds the object is cleared before deleting the object
  • Clear the child object from the parent object before deleting the child if you have cascade="all"

See also Why jsf applications get slow when using a jpa connection

Learn How to add unicode characters to database from hibernate application

Invocation of init method failed – hibernate exception of caching

While working with hibernate you might come up with this error, as I do :(
Fortunately, here is how to make your java happy:

On your hibernate.xml [ or maybe you might named it other ], there is a part describing property:

<property name="hibernateProperties">
 <props>
 <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
 <prop key="hibernate.show_sql">true</prop>
 <prop key="hibernate.c3p0.minPoolSize">5</prop>
 <prop key="hibernate.c3p0.maxPoolSize">200</prop>
 <prop key="hibernate.c3p0.timeout">1800</prop>
 <prop key="hibernate.c3p0.max_statement">50</prop>
 <prop key="hibernate.generate_statistics">true</prop>
 <prop key="hibernate.cache.use_second_level_cache">true</prop>
 <prop key="hibernate.cache.use_query_cache">true</prop>
 <prop key="hibernate.cache.provider_class" >org.hibernate.cache.EhCacheProvider</prop>
 </props>
 </property>

The last two props are the ones we want to blame!!
One way to get rid of this problem would be by just making the values of those to false – hmm… would work but we would miss the capability of caching … Here is the next

Download the ehcache from this location and put it in your classpath.
Update the hibernate.xml file’s property section by adding the following:

<prop key="hibernate.cache.provider_class" >org.hibernate.cache.EhCacheProvider</prop>

Now you+java+hibernate+me HAPPY..
hope would help someone..