Hibernate error org.hibernate.exception.SQLGrammarException: Table ... doesn't exist - java

Java Student here working on a basic Hibernate project.
Server :tomcat
IDE : Eclipse Juno
I'm trying to persist some data into mySql Db but i've been getting an error every time I click the process button.
The error: org.hibernate.exception.SQLGrammarException: Table 'timdowney.requestdatapersistent' doesn't exist
The name of my DB is : timdowney and it DOES exist.
My Db server works fine because i've tested it with other jdbc apps.
So, my question is: why am i getting an error stating that Table 'timdowney.requestdatapersistent' doesn't exist while timdowney is not a table but my DB name ?
fyi: requestdatapersistent is a my bean class
It's a large code, i agree.
Button Method Error
org.hibernate.exception.SQLGrammarException: Table 'timdowney.requestdatapersistent' doesn't exist
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at shared.HelperBaseCh4.invokeButtonMethod(HelperBaseCh4.java:155)
at shared.HelperBaseCh4.executeButtonMethod(HelperBaseCh4.java:124)
at shared.HelperBaseCh4.executeButtonMethod(HelperBaseCh4.java:133)
at shared.HelperBaseCh4.executeButtonMethod(HelperBaseCh4.java:100)
at ch5.persistentData.ControllerHelper.doPost(ControllerHelper.java:128)
at ch5.persistentData.configure.ControllerHelper.doPost(ControllerHelper.java:40)
at ch5.persistentData.configure.Controller.doPost(Controller.java:39)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:947)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1009)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.hibernate.exception.SQLGrammarException: Table 'timdowney.requestdatapersistent' doesn't exist
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:122)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:129)
at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
at com.sun.proxy.$Proxy18.executeQuery(Unknown Source)
at org.hibernate.persister.entity.AbstractEntityPersister.getDatabaseSnapshot(AbstractEntityPersister.java:1469)
at org.hibernate.engine.internal.StatefulPersistenceContext.getDatabaseSnapshot(StatefulPersistenceContext.java:301)
at org.hibernate.engine.internal.ForeignKeys.isTransient(ForeignKeys.java:217)
at org.hibernate.event.internal.AbstractSaveEventListener.getEntityState(AbstractSaveEventListener.java:495)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:100)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:641)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:633)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:629)
at shared.HibernateHelper.updateDB(HibernateHelper.java:135)
at ch5.persistentData.ControllerHelper.processMethod(ControllerHelper.java:101)
... 29 more
Caused by: com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Table 'timdowney.requestdatapersistent' doesn't exist
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2934)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1616)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1708)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3255)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1293)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1428)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122)
... 42 more
hibernate.cfg.xml
<?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="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/timdowney</property>
<property name="connection.username">root</property>
<property name="connection.password">pasapas2005</property>
<property name="c3p0.min_size">1</property>
<property name="c3p0.max_size">5</property>
<property name="c3p0.timeout">300</property>
<property name="c3p0.max_statements">50</property>
<property name="c3p0.idle_test_period">300</property>
</session-factory>
</hibernate-configuration>
My Bean Class
package ch5.persistentData;
import java.io.Serializable;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
#Entity
public class RequestDataPersistent extends shared.PersistentBase implements
Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
protected String hobby;
protected String aversion;
private Long id;
public RequestDataPersistent() {
}
#Id
public Long getId() {
return id;
}
protected void setId(Long id) {
this.id = id;
}
#Pattern(regexp = ".*\\S.*", message = "cannot be empty")
#NotNull
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
#Pattern(regexp = ".*\\S.*", message = "cannot be empty")
#NotNull
public String getAversion() {
return aversion;
}
public void setAversion(String aversion) {
this.aversion = aversion;
}
protected int daysPerWeek;
#Min(value = 1, message = "must be greater than 1, if this is a hobby.")
#Max(value = 7, message = "cannot be greater than 7. A week only has 7 days.")
public int getDaysPerWeek() {
return daysPerWeek;
}
public void setDaysPerWeek(int daysPerWeek) {
this.daysPerWeek = daysPerWeek;
}
}
Controller helper class
package ch5.persistentData.configure;
import ch5.persistentData.RequestDataPersistent;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import shared.HibernateHelper;
public class ControllerHelper
extends ch5.persistentData.ControllerHelper {
public ControllerHelper(
HttpServlet servlet,
HttpServletRequest request,
HttpServletResponse response) {
super(servlet, request, response);
}
static public void initHibernate(HttpServlet servlet) {
boolean create =
Boolean.parseBoolean(servlet.getInitParameter("create"));
if (create) {
HibernateHelper.createTable(RequestDataPersistent.class);
}
HibernateHelper.initSessionFactory(RequestDataPersistent.class);
}
#Override
public void doGet()
throws ServletException, java.io.IOException
{
super.doGet();
}
#Override
public void doPost()
throws ServletException, java.io.IOException
{
super.doPost();
}
}
HiernateHelper class
package shared;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.criterion.Restrictions;
public class HibernateHelper {
static protected Logger log = Logger
.getLogger("bytesizebook.webdev.hibernate");
static protected List<Class> listClasses = new ArrayList<Class>();
static protected SessionFactory sessionFactory;
static public void initSessionFactory(Properties props, Class... mappings) {
if (addMappings(listClasses, mappings)) {
closeSessionFactory(sessionFactory);
sessionFactory = createFactory(props, listClasses);
}
}
static public void initSessionFactory(Class... mappings) {
initSessionFactory(null, mappings);
}
static public void createTable(Properties props, Class... mappings) {
List<Class> tempList = new ArrayList<Class>();
SessionFactory tempFactory = null;
addMappings(tempList, mappings);
if (props == null) {
props = new Properties();
}
props.setProperty(Environment.HBM2DDL_AUTO, "create");
tempFactory = createFactory(props, tempList);
closeSessionFactory(tempFactory);
}
static public void createTable(Class... mappings) {
createTable(null, mappings);
}
static protected boolean addMappings(List<Class> list, Class... mappings) {
boolean bNewClass = false;
for (Class mapping : mappings) {
if (!list.contains(mapping)) {
list.add(mapping);
bNewClass = true;
}
}
return bNewClass;
}
static protected SessionFactory createFactory(Properties props,
List<Class> list) {
SessionFactory factory = null;
Configuration cfg = new Configuration();
try {
if (props != null) {
cfg.addProperties(props);
}
configureFromFile(cfg);
for (Class mapping : list) {
cfg.addAnnotatedClass(mapping);
}
factory = buildFactory(cfg);
} catch (Exception ex) {
// Make sure you log the exception, as it might be swallowed
log.error("SessionFactory creation failed.", ex);
closeSessionFactory(factory);
factory = null;
// hibernate has a runtime exception for handling problems with
// initialisation. Cast the ex to HibernateException and raise,
// since the root problem is a Hibernate problem.
throw new HibernateException(ex);
}
return factory;
}
static protected void configureFromFile(Configuration cfg) {
try {
cfg.configure();
} catch (HibernateException ex) {
if (ex.getMessage().equals("/hibernate.cfg.xml not found")) {
log.warn(ex.getMessage());
} else {
log.error("Error in hibernate " + "configuration file.", ex);
throw ex;
}
}
}
static protected SessionFactory buildFactory(Configuration cfg)
throws Exception {
SessionFactory factory = null;
try {
factory = cfg.buildSessionFactory();
} catch (Exception ex) {
closeSessionFactory(factory);
factory = null;
throw ex;
}
return factory;
}
static public void closeSessionFactory(SessionFactory factory) {
if (factory != null) {
factory.close();
}
}
static public void closeFactory() {
closeSessionFactory(sessionFactory);
}
static public void updateDB(Object obj) {
Session session = null;
try {
session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.saveOrUpdate(obj);
tx.commit();
} finally {
if (session != null) {
session.close();
}
}
}
static public void updateDB(java.util.List list) {
Session session = null;
try {
session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
for (Object obj : list) {
session.saveOrUpdate(obj);
}
tx.commit();
} finally {
if (session != null) {
session.close();
}
}
}
static public void saveDB(Object obj) {
Session session = null;
try {
session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.save(obj);
tx.commit();
} finally {
if (session != null) {
session.close();
}
}
}
static public void removeDB(Object obj) {
Session session = null;
try {
session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.delete(obj);
tx.commit();
} finally {
if (session != null) {
session.close();
}
}
}
static public java.util.List getListData(Class classBean, String strKey,
Object value) {
java.util.List result = new java.util.ArrayList();
Session session = null;
try {
session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Criteria criteria = session.createCriteria(classBean);
if (strKey != null) {
criteria.add(Restrictions.like(strKey, value));
}
result = criteria.list();
tx.commit();
} finally {
if (session != null) {
session.close();
}
}
return result;
}
static public java.util.List getListData(Class classBean, String strKey1,
Object value1, String strKey2, Object value2) {
java.util.List result = new java.util.ArrayList();
boolean withParent = false;
int age = 0;
Session session = null;
try {
session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Criteria criteria = session.createCriteria(classBean);
if (strKey1 != null) {
criteria.add(Restrictions.like(strKey1, value1));
}
if (strKey2 != null) {
criteria.add(Restrictions.like(strKey2, value2));
}
result = criteria.list();
tx.commit();
} finally {
if (session != null) {
session.close();
}
}
return result;
}
static public java.util.List getListData(Class classBean) {
return getListData(classBean, null, null);
}
static public Object getFirstMatch(Class classBean, String strKey,
Object value) {
Object result = null;
Session session = null;
try {
session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Criteria criteria = session.createCriteria(classBean);
if (strKey != null) {
criteria.add(Restrictions.like(strKey, value));
}
criteria.setMaxResults(1);
result = criteria.uniqueResult();
tx.commit();
} finally {
if (session != null) {
session.close();
}
}
return result;
}
static public Object getFirstMatch(Object data, String strKey, Object value) {
return getFirstMatch(data.getClass(), strKey, value);
}
static public Object getKeyData(Class beanClass, long itemId) {
Object data = null;
Session session = sessionFactory.openSession();
data = session.get(beanClass, itemId);
session.close();
return data;
}
static public boolean isSessionOpen() {
return sessionFactory != null;
}
}
new stacktrace after adding #Table annotation in my bean class
Button Method Error
org.hibernate.PropertyAccessException: IllegalArgumentException occurred while calling setter of ch5.persistentData.RequestDataPersistent.id
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at shared.HelperBaseCh4.invokeButtonMethod(HelperBaseCh4.java:155)
at shared.HelperBaseCh4.executeButtonMethod(HelperBaseCh4.java:124)
at shared.HelperBaseCh4.executeButtonMethod(HelperBaseCh4.java:133)
at shared.HelperBaseCh4.executeButtonMethod(HelperBaseCh4.java:100)
at ch5.persistentData.ControllerHelper.doPost(ControllerHelper.java:128)
at ch5.persistentData.configure.ControllerHelper.doPost(ControllerHelper.java:40)
at ch5.persistentData.configure.Controller.doPost(Controller.java:39)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:947)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1009)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.hibernate.PropertyAccessException: IllegalArgumentException occurred while calling setter of ch5.persistentData.RequestDataPersistent.id
at org.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:119)
at org.hibernate.mapping.Component$ValueGenerationPlan.execute(Component.java:436)
at org.hibernate.id.CompositeNestedGeneratedValueGenerator.generate(CompositeNestedGeneratedValueGenerator.java:121)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:118)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:204)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:189)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:114)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:641)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:633)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:629)
at shared.HibernateHelper.updateDB(HibernateHelper.java:130)
at ch5.persistentData.ControllerHelper.processMethod(ControllerHelper.java:101)
... 29 more
Caused by: java.lang.IllegalArgumentException: argument type mismatch
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:65)
... 41 more

org.hibernate.exception.SQLGrammarException: Table 'timdowney.requestdatapersistent' doesn't exist
Error says schemaname.tablename does not exist, so your schema is timdowney and table name is requestdatapersistent. Since you did not specify any table in Entity it is using bean name as entity name, you need to do either of following:
Create a table named requestdatapersistent
If there is a different table name then provide in annotation using following:
#Entity
#Table(name="request_data_persistent")
Hoping this solves your problem.
Cheers !!

if annotation doesn't work for you, you may try creating hibernate mapping file similar to the below:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="ch5.persistentData.RequestDataPersistent"
table="tablename" catalog="timdowney ">
<id name="ID" type="java.lang.Long">
<column name="id" length="10" not-null="true" unique="true" />
</id>
<property name="EventName" type="String">
<column name="eventname" length="10" not-null="true" unique="false" />
</property>
<property name="hobby" type="String">
<column name="hobby" length="20" not-null="true"
unique="false" />
</property>
....and so on
</class>
</hibernate-mapping>

Related

upgrading from Hiberante 3 to Hibernate 4 can't persist data to datatbase

OK, we have an Hibernate 3 application that I am trying to update to hibernate 4. I can retrieve the data without any problem, but cannot add or update the database. I don't get any error messages, the transaction seems to work, but nothing gets changed in the database. Some help would be greatly appreciated.
Here's the config file hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">false</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.connection.datasource">jdbc/misc</property>
<property name="hibernate.jndi.url">iiop://127.0.0.1:3700</property>
<property name="hibernate.transaction.factory_class">org.hibernate.transaction.JTATransactionFactory</property>
<property name="hibernate.transaction.manager_lookup_class">org.hibernate.transaction.SunONETransactionManagerLookup</property>
<mapping resource="sponsor.hbm.xml"/>
<mapping resource="portfolio.hbm.xml"/>
<mapping resource="clientID.hbm.xml"/>
<mapping resource="legacyID.hbm.xml"/>
<mapping resource="badClient.hbm.xml"/>
<mapping resource="language.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Here's a sam;ole map file of the table I am currently working with sponsor.hbm.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.lingosys.hibernate.Sponsor" table="sponsor">
<id name="companyID" type="integer">
<generator class="assigned"/>
</id>
<property name="companyName" type="string"/>
<property name="sponsorID" type="integer"/>
<property name="sponsorName" type="string"/>
<property name="status" type="string"/>
</class>
</hibernate-mapping>
Here's the class for creating the session factory HibenateUtil.java:
package com.lingosys.hibernate;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
/**
* Hibernate Utility class with a convenient method to get Session Factory object.
*
* #author mphoenix
*/
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from standard (hibernate.cfg.xml)
// config file.
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Here's the dao file SponsorDAO.java:
package com.lingosys.hibernate;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
/**
*
* #author mphoenix
*/
public class SponsorDAO {
private Session session = null;
public SponsorDAO() {
}
private void startOperation() {
session = HibernateUtil.getSessionFactory().openSession();
}
public void create(Sponsor sponsor) {
startOperation();
session.saveOrUpdate("Sponsor", sponsor);
session.close();
}
public void update(Sponsor sponsor) {
startOperation();
session.update("Sponsor", sponsor);
session.close();
}
public Sponsor findSponsor(int id) {
startOperation();
Sponsor sponsor = (Sponsor) session.get(Sponsor.class, new Integer(id));
session.close();
return sponsor;
}
public List <Sponsor> findAllSponsors() {
List <Sponsor> sponsors = null;
startOperation();
Query query = session.createQuery("from Sponsor");
sponsors = query.list();
session.close();
return sponsors;
}
public void delete(Sponsor sponsor) {
startOperation();
session.delete(sponsor);
session.close();
}
}
Here's the create transaction code:
UserTransaction tx = null;
try {
tx = (UserTransaction)new InitialContext()
.lookup("java:comp/UserTransaction");
tx.begin();
dao.create(sponsor);
tx.commit();
} catch (HibernateException ex) {
try {
tx.rollback();
} catch (Exception ex2) {
facesCtx.addMessage(null, new FacesMessage("Error on rollback.",
ex2.toString()));
}
facesCtx.addMessage(null, new FacesMessage("Hibernate Error.",
ex.toString()));
return null;
} catch (Exception ex) {
facesCtx.addMessage(null, new FacesMessage("Non-hibernate Error.",
ex.toString()));
return null;
}
Here's a retrieval transaction:
try {
tx = (UserTransaction)new InitialContext()
.lookup("java:comp/UserTransaction");
tx.begin();
setSponsorItems(new ArrayList<Sponsor>());
List<Sponsor> sponsors = dao.findAllSponsors();
for (Sponsor aSponsor : sponsors) {
if (companyItemsMap.get(aSponsor.getCompanyID()) != null) {
getSponsorItems().add(aSponsor);
}
}
tx.commit();
} catch (HibernateException ex) {
try {
tx.rollback();
} catch (Exception ex2) {
facesCtx.addMessage(null, new FacesMessage(ex2.toString()));
}
facesCtx.addMessage(null, new FacesMessage(ex.toString()));
return false;
} catch (Exception ex) {
facesCtx.addMessage(null, new FacesMessage(ex.toString()));
return false;
}
And finally the object being mapped to Sponsor.java
package com.lingosys.hibernate;
import java.io.Serializable;
/**
*
* #author mphoenix
*/
public class Sponsor implements Serializable {
private int companyID;
private String companyName;
private int sponsorID;
private String sponsorName;
private String status;
public Sponsor() {
}
public int getCompanyID() {
return companyID;
}
public void setCompanyID(int companyID) {
this.companyID = companyID;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public int getSponsorID() {
return sponsorID;
}
public void setSponsorID(int sponsorID) {
this.sponsorID = sponsorID;
}
public String getSponsorName() {
return sponsorName;
}
public void setSponsorName(String sponsorName) {
this.sponsorName = sponsorName;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Sponsor other = (Sponsor) obj;
if (this.companyID != other.companyID) {
return false;
}
return true;
}
#Override
public int hashCode() {
int hash = 5;
hash = 97 * hash + this.companyID;
return hash;
}
//DEBUG CASPERW
#Override
public String toString() {
return "CompanyID: "+companyID+" CompanyName: "+companyName+" SponsorID: "+sponsorID+" SponsorName: "+sponsorName+"\n";
}
}

org.hibernate.exception.SQLGrammarException: could not extract ResultSet

I have implemented a simple application in Hibernate-4. This application retrieve the value from a table. But when I try to get the record with this
(Booking) session.get(Booking.class, 3740456);
it gives me exception
INFO: HHH000327: Error performing load command : org.hibernate.exception.SQLGrammarException: could not extract ResultSet
So, to verify into the database regarding table and column name, I copy the query from the log statement and execute it. It gives me proper output.
I checked several questions & answers related to this question, but could able to derive the solution.
Hibernate.cfg.xml
<?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="connection.url">jdbc:oracle:thin:#SHKG9072DB:5030:TMSD10G2</property>
<property name="connection.username">ICTDEV$EDI_APP</property>
<property name="connection.password">p2II9JLIaea06</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hibernate.temp.use_jdbc_metadata_defaults">false</property>
<property name = "hibernate.jdbc.lob.non_contextual_creation">true</property>
<property name="connection.pool_size">1</property>
<property name="current_session_context_class">thread</property>
<mapping class="com.hibernate.demo.Booking"/>
</session-factory>
</hibernate-configuration>
Booking.java
package com.hibernate.demo;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="EDI_IN_BOOKING")
public class Booking {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
private int id;
#Column(name="SITE_AN")
private String site;
#Column(name="EVENT_ID")
private int eventId;
#Column(name="EVENT_DETAIL_ID")
private int eventDetailId;
#Column(name="RECORD_SEQUENCE_ID")
private int recordSequenceId;
#Column(name="RECORD_TYPE_N")
int recordType;
#Column(name="EDI_SENDER_AN")
String sender;
#Column(name="EDI_RECIPIENT_AN")
String recipient;
#Column(name="PARTNER_C")
String partner;
#Column(name="SENDER_SEQUENCE_AN")
String senderSequence;
public String getSite() {
return site;
}
public void setSite(String site) {
this.site = (site);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = (id);
}
public int getEventId() {
return eventId;
}
public void setEventId(int eventId) {
this.eventId = (eventId);
}
public int getEventDetailId() {
return eventDetailId;
}
public void setEventDetailId(int eventDetailId) {
this.eventDetailId = (eventDetailId);
}
public int getRecordSequenceId() {
return recordSequenceId;
}
public void setRecordSequenceId(int recordSequenceId) {
this.recordSequenceId = (recordSequenceId);
}
public int getRecordType() {
return recordType;
}
public void setRecordType(int recordType) {
this.recordType = (recordType);
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = (sender);
}
public String getRecipient() {
return recipient;
}
public void setRecipient(String recipient) {
this.recipient = (recipient);
}
public String getPartner() {
return partner;
}
public void setPartner(String partner) {
this.partner = (partner);
}
public String getSenderSequence() {
return senderSequence;
}
public void setSenderSequence(String senderSequence) {
this.senderSequence = (senderSequence);
}
}
Main.java
package com.hibernate.demo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
System.out.println("Trying to create a test connection with the database.");
Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
serviceRegistryBuilder.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Booking booking = (Booking) session.get(Booking.class, 3740456);
System.out.println(booking.getEventDetailId());
}
}
Table description
desc EDi_IN_BOOKING
ID NOT NULL NUMBER
EVENT_ID NOT NULL NUMBER
EVENT_DETAIL_ID NOT NULL NUMBER
RECORD_SEQUENCE_ID NOT NULL NUMBER
RECORD_TYPE_N NUMBER(1)
SITE_AN VARCHAR2(10)
EDI_SENDER_AN VARCHAR2(35)
EDI_RECIPIENT_AN VARCHAR2(35)
PARTNER_C VARCHAR2(20)
SENDER_SEQUENCE_AN VARCHAR2(15)
Query from log (this gives correct output)
select
booking0_.id as id1_0_0_,
booking0_.EVENT_DETAIL_ID as EVENT_DETAIL_ID2_0_0_,
booking0_.EVENT_ID as EVENT_ID3_0_0_,
booking0_.PARTNER_C as PARTNER_C4_0_0_,
booking0_.EDI_RECIPIENT_AN as EDI_RECIPIENT_AN5_0_0_,
booking0_.RECORD_SEQUENCE_ID as RECORD_SEQUENCE_ID6_0_0_,
booking0_.RECORD_TYPE_N as RECORD_TYPE_N7_0_0_,
booking0_.EDI_SENDER_AN as EDI_SENDER_AN8_0_0_,
booking0_.SENDER_SEQUENCE_AN as SENDER_SEQUENCE_AN9_0_0_,
booking0_.site_an as site_an10_0_0_
from
EDI_IN_BOOKING booking0_
where
booking0_.id=3740456;
exception
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate:
select
booking0_.id as id1_0_0_,
booking0_.EVENT_DETAIL_ID as EVENT_DETAIL_ID2_0_0_,
booking0_.EVENT_ID as EVENT_ID3_0_0_,
booking0_.PARTNER_C as PARTNER_C4_0_0_,
booking0_.EDI_RECIPIENT_AN as EDI_RECIPIENT_AN5_0_0_,
booking0_.RECORD_SEQUENCE_ID as RECORD_SEQUENCE_ID6_0_0_,
booking0_.RECORD_TYPE_N as RECORD_TYPE_N7_0_0_,
booking0_.EDI_SENDER_AN as EDI_SENDER_AN8_0_0_,
booking0_.SENDER_SEQUENCE_AN as SENDER_SEQUENCE_AN9_0_0_,
booking0_.site_an as site_an10_0_0_
from
EDI_IN_BOOKING booking0_
where
booking0_.id=?
May 22, 2015 10:49:43 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 904, SQLState: 42000
May 22, 2015 10:49:43 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: ORA-00904: "BOOKING0_"."SITE_AN": invalid identifier
May 22, 2015 10:49:43 AM org.hibernate.event.internal.DefaultLoadEventListener onLoad
INFO: HHH000327: Error performing load command : org.hibernate.exception.SQLGrammarException: could not extract ResultSet
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:123)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:91)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.getResultSet(AbstractLoadPlanBasedLoader.java:449)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeQueryStatement(AbstractLoadPlanBasedLoader.java:202)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:137)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:102)
at org.hibernate.loader.entity.plan.AbstractLoadPlanBasedEntityLoader.load(AbstractLoadPlanBasedEntityLoader.java:186)
at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:4126)
at org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:503)
at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:468)
at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:213)
at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:275)
at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:151)
at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1106)
at org.hibernate.internal.SessionImpl.access$2000(SessionImpl.java:176)
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.load(SessionImpl.java:2587)
at org.hibernate.internal.SessionImpl.get(SessionImpl.java:991)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:356)
at $Proxy7.get(Unknown Source)
at com.dpworld.demo.Main.main(Main.java:23)
Caused by: java.sql.SQLException: ORA-00904: "BOOKING0_"."SITE_AN": invalid identifier
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)
at oracle.jdbc.ttc7.TTIoer.processError(TTIoer.java:289)
at oracle.jdbc.ttc7.Oall7.receive(Oall7.java:589)
at oracle.jdbc.ttc7.TTC7Protocol.doOall7(TTC7Protocol.java:1957)
at oracle.jdbc.ttc7.TTC7Protocol.parseExecuteDescribe(TTC7Protocol.java:850)
at oracle.jdbc.driver.OracleStatement.doExecuteQuery(OracleStatement.java:2555)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:2896)
at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:644)
at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:570)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:82)
... 22 more
Is your database configured with case sensitive columns? That could be one reason why Oracle is throwing an "invalid identifier" error
Check your table creating script.
Why is site_an in lowercase in the select such as booking0_.site_an as site_an10_0_0_ while all other column names are in uppercase. I think it may be an uppercase "i" issue.
select
booking0_.id as id1_0_0_,
booking0_.EVENT_DETAIL_ID as EVENT_DETAIL_ID2_0_0_,
booking0_.EVENT_ID as EVENT_ID3_0_0_,
booking0_.PARTNER_C as PARTNER_C4_0_0_,
booking0_.EDI_RECIPIENT_AN as EDI_RECIPIENT_AN5_0_0_,
booking0_.RECORD_SEQUENCE_ID as RECORD_SEQUENCE_ID6_0_0_,
booking0_.RECORD_TYPE_N as RECORD_TYPE_N7_0_0_,
booking0_.EDI_SENDER_AN as EDI_SENDER_AN8_0_0_,
booking0_.SENDER_SEQUENCE_AN as SENDER_SEQUENCE_AN9_0_0_,
booking0_.site_an as site_an10_0_0_

Hibernate No Session (No Dependencies)

I have the following JPA entity (generated with Netbeans):
package com.tsystems.tf.db.models;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* #author johorvat
*/
#Entity
#Table(name = "TABLE1")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Testcase.findAll", query = "SELECT t FROM Testcase t")
})
public class Testcase implements Serializable {
private static final long serialVersionUID = 1L;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Id
#Basic(optional = false)
#Column(name = "TESTCASE_ID")
private BigDecimal testcaseId;
#Basic(optional = false)
#Column(name = "TESTCASE_NAME")
private String testcaseName;
#Basic(optional = false)
#Column(name = "CREATOR")
private String creator;
#Basic(optional = false)
#Column(name = "CREATED_AT")
#Temporal(TemporalType.TIMESTAMP)
private Date createdAt;
#Column(name = "LAST_RUN")
#Temporal(TemporalType.TIMESTAMP)
private Date lastRun;
#Column(name = "LAST_RUN_RESULT")
private Character lastRunResult;
#Column(name = "INPUT")
private String input;
#Column(name = "OUTPUT")
private String output;
public Testcase() {
}
public Testcase(BigDecimal testcaseId) {
this.testcaseId = testcaseId;
}
public Testcase(BigDecimal testcaseId, String testcaseName, String creator, Date createdAt) {
this.testcaseId = testcaseId;
this.testcaseName = testcaseName;
this.creator = creator;
this.createdAt = createdAt;
}
public BigDecimal getTestcaseId() {
return testcaseId;
}
public void setTestcaseId(BigDecimal testcaseId) {
this.testcaseId = testcaseId;
}
public String getTestcaseName() {
return testcaseName;
}
public void setTestcaseName(String testcaseName) {
this.testcaseName = testcaseName;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getLastRun() {
return lastRun;
}
public void setLastRun(Date lastRun) {
this.lastRun = lastRun;
}
public Character getLastRunResult() {
return lastRunResult;
}
public void setLastRunResult(Character lastRunResult) {
this.lastRunResult = lastRunResult;
}
public String getInput() {
return input;
}
public void setInput(String input) {
this.input = input;
}
public String getOutput() {
return output;
}
public void setOutput(String output) {
this.output = output;
}
#Override
public int hashCode() {
int hash = 0;
hash += (testcaseId != null ? testcaseId.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Testcase)) {
return false;
}
Testcase other = (Testcase) object;
if ((this.testcaseId == null && other.testcaseId != null) || (this.testcaseId != null && !this.testcaseId.equals(other.testcaseId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.tsystems.tf.db.models.Testcase[ testcaseId=" + testcaseId + " ]";
}
}
I try to implement CRUD operations for this entity using Hibernate but I get LazyEvaluationException. There are NO references. Its only 1 table in the database... I can query but when I try to issue update the exception is being thrown. Now I have a really naive implementation that looks like the following:
package com.tsystems.tf.dao.impl;
import com.tsystems.tf.dao.ITestcaseDAO;
import com.tsystems.tf.db.models.Testcase;
import java.math.BigDecimal;
import java.util.Collection;
import javax.transaction.Transactional;
import org.apache.catalina.tribes.util.Arrays;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.jboss.logging.Logger;
public class TestcaseDAOImpl implements ITestcaseDAO {
private static final SessionFactory sessionFactory;
static {
Configuration configuration = new Configuration();
configuration = configuration.configure();
StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder();
registryBuilder = registryBuilder.applySettings(configuration.getProperties());
StandardServiceRegistry registry = registryBuilder.build();
sessionFactory = configuration.buildSessionFactory(registry);
}
#Override
public Collection<Testcase> getAllTestcase() {
Session session = sessionFactory.openSession();
Transaction transaction = null;
Collection<Testcase> testcaseCollection = null;
try {
transaction = session.beginTransaction();
Query query = session.getNamedQuery("Testcase.findAll");
testcaseCollection = query.list();
transaction.commit();
} catch (final HibernateException ex) {
Logger.getLogger(TestcaseDAOImpl.class)
.error(ex.getMessage() + "\n" + Arrays.toString(ex.getStackTrace()));
if (transaction != null)
transaction.rollback();
}
session.close();
return testcaseCollection;
}
#Override
public void createTestcase(Testcase testcase) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public Testcase readTestcase(BigDecimal id) {
Session session = sessionFactory.openSession();
Transaction transaction = null;
Testcase testcase = null;
try {
transaction = session.beginTransaction();
testcase = (Testcase) session.load(Testcase.class, id);
transaction.commit();
} catch (final HibernateException ex) {
Logger.getLogger(TestcaseDAOImpl.class)
.error(ex.getMessage() + "\n" + Arrays.toString(ex.getStackTrace()));
if (transaction != null)
transaction.rollback();
}
session.close();
return testcase;
}
#Override
public void updateTestcase(Testcase testcase) {
Session session = sessionFactory.openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.update(testcase);
transaction.commit();
} catch (final HibernateException ex) {
Logger.getLogger(TestcaseDAOImpl.class)
.error(ex.getMessage() + "\n" + Arrays.toString(ex.getStackTrace()));
if (transaction != null)
transaction.rollback();
}
session.close();
}
#Override
public void deleteTestcase(BigDecimal testcaseId) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
When the update is being called bamm No Session. Why is this happening? GetAll succeeds nice and smooth but that's all to it. Everything else returns in No Session error in my logs.
StackTrace:
14-Nov-2014 16:54:43.012 WARNING [http-apr-8080-exec-148] com.sun.faces.context.SessionMap.put JSF1063: WARNING! Setting non-serializable attribute value into HttpSession (key: testcaseProvider, value class: com.tsystems.tf.beans.TestcaseProvider).
14-Nov-2014 16:54:46.812 WARNING [http-apr-8080-exec-148] com.sun.faces.lifecycle.InvokeApplicationPhase.execute #{testcaseProvider.updateTestcase()}: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
javax.faces.FacesException: #{testcaseProvider.updateTestcase()}: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:277)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2403)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2392)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: javax.faces.el.EvaluationException: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
... 29 more
Caused by: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:164)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:285)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
at com.tsystems.tf.db.models.Testcase_$$_jvsta1c_0.setTestcaseName(Testcase_$$_jvsta1c_0.java)
at com.tsystems.tf.beans.TestcaseProvider.updateTestcase(TestcaseProvider.java:60)
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:483)
at org.apache.el.parser.AstValue.invoke(AstValue.java:245)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:277)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
... 30 more
14-Nov-2014 16:54:46.832 SEVERE [http-apr-8080-exec-148] com.sun.faces.context.AjaxExceptionHandlerImpl.handlePartialResponseError javax.faces.el.EvaluationException: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:277)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2403)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2392)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:164)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:285)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
at com.tsystems.tf.db.models.Testcase_$$_jvsta1c_0.setTestcaseName(Testcase_$$_jvsta1c_0.java)
at com.tsystems.tf.beans.TestcaseProvider.updateTestcase(TestcaseProvider.java:60)
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:483)
at org.apache.el.parser.AstValue.invoke(AstValue.java:245)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:277)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
... 30 more
replace your static block by a before() method, and add the session creation at the end of it :
#Before
public void before() {
Configuration configuration = new Configuration();
configuration = configuration.configure();
StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder();
registryBuilder = registryBuilder.applySettings(configuration.getProperties());
StandardServiceRegistry registry = registryBuilder.build();
sessionFactory = configuration.buildSessionFactory(registry);
session = sessionFactory.openSession();
}
and an after() method :
#After
public void after {
session.close();
sessionFactory.close();
}
And of course, remove all open/close session in each test.

hibernate doesn't see a setter

I am new to hibernate and I have stupid problem. My files:
hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.PostgreSQLDialect
</property>
<property name="hibernate.connection.driver_class">
org.postgresql.Driver
</property>
<!-- Assume test is the database name -->
<property name="hibernate.connection.url">
jdbc:postgresql://localhost/booktown
</property>
<property name="hibernate.connection.username">
mirek
</property>
<mapping resource="Books.hbm.xml"/>
</session-factory>
</hibernate-configuration>
books.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Books" table="books">
<meta attribute="Książki w booktown">
This class contains the employee detail.
</meta>
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="title" column="title" type="string"/>
<property name="author_id" column="author_id" type="int"/>
<property name="subject_id" column="subject_id" type="int"/>
</class>
</hibernate-mapping>
Books.java
public class Books
{
private int id;
private String title;
private int author_id;
private int subject_id;
public Books(String title, int author_id, int subject_id)
{
this.title = title;
this.author_id = author_id;
this.subject_id = subject_id;
}
public void setId(int id)
{
this.id = id;
}
public void setTitle(String title)
{
this.title = title;
}
public void setAuthorId(int author_id)
{
this.author_id = author_id;
}
public void setSubjectId(int subject_id)
{
this.subject_id = subject_id;
}
public int getId()
{
return id;
}
public String getTitle()
{
return title;
}
public int getAuthorId()
{
return author_id;
}
public int getSubjectId()
{
return subject_id;
}
}
and Booktown.java
import java.util.Iterator;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class Booktown
{
private static SessionFactory factory;
private static ServiceRegistry serviceRegistry;
public static void main(String[] args)
{
try
{
//private static SessionFactory configureSessionFactory() throws HibernateException {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
factory = configuration.buildSessionFactory(serviceRegistry);
//return factory;
//factory = new Configuration().configure().buildSessionFactory();
}
catch (Throwable ex)
{
System.err.println("Failed to create sessionFactory object." + ex.toString());
throw new ExceptionInInitializerError(ex);
}
Booktown BT = new Booktown();
/* Add few employee records in database */
Integer bID1 = BT.addBook(10, "Jakiś napis", 10, 30);
Integer bID2 = BT.addBook(20, "Jakiś inny napis", 10, 50);
//Integer bID3 = BT.addBook(30, "John", 10000, 14);
/* List down all the employees */
BT.listBooks();
/* Update employee's records */
BT.updateBook(bID1, 5000);
/* Delete an employee from the database */
BT.deleteBook(bID2);
/* List down new list of the employees */
BT.listBooks();
}
/* Method to CREATE a book in the database */
public Integer addBook(int bid, String fname, int lname, int salary)
{
Session session = factory.openSession();
Transaction tx = null;
Integer bID = null;
try
{
tx = session.beginTransaction();
Books book = new Books(fname, lname, salary);
bid = (Integer) session.save(book);
tx.commit();
}
catch (HibernateException e)
{
if (tx != null)
tx.rollback();
e.printStackTrace();
}
finally
{
session.close();
}
return bID;
}
/* Method to READ all the books */
public void listBooks()
{
Session session = factory.openSession();
Transaction tx = null;
try
{
tx = session.beginTransaction();
List<Books> books = session.createQuery("FROM books").list();
for (Iterator<Books> iterator = books.iterator(); iterator.hasNext();)
{
Books book = (Books) iterator.next();
System.out.print("First Name: " + book.getTitle());
System.out.print(" Last Name: " + book.getAuthorId());
System.out.println(" Salary: " + book.getSubjectId());
}
tx.commit();
}
catch (HibernateException e)
{
if (tx != null)
tx.rollback();
e.printStackTrace();
}
finally
{
session.close();
}
}
/* Method to UPDATE author for a book */
public void updateBook(Integer bID, int auth)
{
Session session = factory.openSession();
Transaction tx = null;
try
{
tx = session.beginTransaction();
Books book = (Books) session.get(Books.class, bID);
book.setAuthorId(auth);
session.update(book);
tx.commit();
}
catch (HibernateException e)
{
if (tx != null)
tx.rollback();
e.printStackTrace();
}
finally
{
session.close();
}
}
/* Method to DELETE a book from the records */
public void deleteBook(Integer bID)
{
Session session = factory.openSession();
Transaction tx = null;
try
{
tx = session.beginTransaction();
Books book = (Books) session.get(Books.class, bID);
session.delete(book);
tx.commit();
}
catch (HibernateException e)
{
if (tx != null)
tx.rollback();
e.printStackTrace();
}
finally
{
session.close();
}
}
}
Code is compiling but at run I get:
> paź 15, 2013 8:44:38 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Failed to create sessionFactory object.org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister
Exception in thread "main" java.lang.ExceptionInInitializerError
at Booktown.main(Booktown.java:34)
Caused by: org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister
at org.hibernate.persister.internal.PersisterFactoryImpl.create(PersisterFactoryImpl.java:185)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:135)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:385)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1790)
at Booktown.main(Booktown.java:25)
Caused by: org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:138)
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructDefaultTuplizer(EntityTuplizerFactory.java:188)
at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:341) at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:507)
at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:146)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at org.hibernate.persister.internal.PersisterFactoryImpl.create(PersisterFactoryImpl.java:163)
... 4 more
Caused by: java.lang.reflect.InvocationTargetException at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:135)
... 13 more
Caused by: org.hibernate.PropertyNotFoundException: Could not find a getter for author_id in class Books
at org.hibernate.property.BasicPropertyAccessor.createGetter(BasicPropertyAccessor.java:316)
at org.hibernate.property.BasicPropertyAccessor.getGetter(BasicPropertyAccessor.java:310)
at org.hibernate.mapping.Property.getGetter(Property.java:321)
at org.hibernate.tuple.entity.PojoEntityTuplizer.buildPropertyGetter(PojoEntityTuplizer.java:444)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.<init>(AbstractEntityTuplizer.java:200)
at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:82)
... 18 more
I found similar problem there was no setter. In my case system says that there is no getter for author_id but it is at line 45 in Books.java.
Could sb tells me what is wrong? Maybe there is an other cause which I don't see...
public int getAuthorId()
{
return author_id;
}
should be (observe, author_id)
public int getAuthor_id()
{
return author_id;
}
OR update XML as #Boris the spider commented.
As far as I know Hibernate requires a no-arg constructor which your Books class does seem to have. So even if you get the save part working I think your code will fail when you attempt to load.
Thus, create a constructor:
public Books(){
}
Why does Hibernate require no argument constructor?
Also, as pointed out previously ditch the XML and use JPA annotations. In line with standard Java conventions rename Books to Book and remove the _ from your variable names.
Alan
I had once this problem and I fix it like that:
You should Generate Constructor, Getters and Setters in NetBeans IDE ( I'm working with IDE is netbeans) so you have to press shortcut ALT+Insert (CTLRL+I on Mac). After invoking the shortcut, all possible generators are offered.

Getting "org.hibernate.TransactionException: nested transactions not supported" error when deleting

When running removeUserFromConference method getting this exception:
04/06/2012 00:20:48 org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [ConferenceServlet] in context with path [/conf4u] threw exception
org.hibernate.TransactionException: nested transactions not supported
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.begin(AbstractTransactionImpl.java:152)
at org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1396)
at sun.reflect.GeneratedMethodAccessor39.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:352)
at $Proxy12.beginTransaction(Unknown Source)
at daos.ConferenceDao.isConferenceNameExists(ConferenceDao.java:129)
at servlets.ConferenceServlet.removeUser(ConferenceServlet.java:232)
at servlets.ConferenceServlet.processRequest(ConferenceServlet.java:79)
at servlets.ConferenceServlet.doPost(ConferenceServlet.java:433)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:928)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:539)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:298)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
04/06/2012 00:27:15 org.apache.catalina.core.StandardContext reload
INFO: Reloading Context with name [/conf4u] has started
04/06/2012 00:27:15 org.apache.catalina.loader.WebappClassLoader clearReferencesJdbc
SEVERE: The web application [/conf4u] registered the JDBC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
04/06/2012 00:27:15 org.apache.catalina.core.StandardContext reload
INFO: Reloading Context with name [/conf4u] is completed
Dao method:
public void removeUserFromConference(Conference conference, User user) {
ConferencesUsers conferenceUser = getConferenceUser(conference, user);
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.delete(conferenceUser);
session.getTransaction().commit();
}
The model class:
#Entity
#Table( name = "Conferences_Users" )
public class ConferencesUsers implements Serializable {
private static final long serialVersionUID = -3401337605668111437L;
private Conference conference;
private User user;
private int userRole;
private UserAttendanceStatus attendanceStatus;
private boolean notifiedByMail;
ConferencesUsers() {} //not public on purpose!
public ConferencesUsers(Conference conf, User user, int userRole) {
this.conference = conf;
this.user = user;
this.userRole = userRole;
this.attendanceStatus = null;
this.notifiedByMail = false;
}
public ConferencesUsers(Conference conf, User user, int userRole, UserAttendanceStatus attendanceStatus, boolean notifiedByMail) {
this.conference = conf;
this.user = user;
this.userRole = userRole;
this.attendanceStatus = attendanceStatus;
this.notifiedByMail = notifiedByMail;
}
#Id
#ManyToOne(cascade = CascadeType.ALL)
public Conference getConference() {
return conference;
}
public void setConference(Conference conference) {
this.conference = conference;
}
#Id
#ManyToOne(cascade = CascadeType.ALL)
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
#Enumerated(EnumType.STRING)
public int getUserRole() {
return userRole;
}
public void setUserRole(int userRole) {
this.userRole = userRole;
}
#Nullable
public boolean isNotifiedByMail() {
return notifiedByMail;
}
public void setNotifiedByMail(boolean notifiedByMail) {
this.notifiedByMail = notifiedByMail;
}
public UserAttendanceStatus getAttendanceStatus() {
return attendanceStatus;
}
public ConferencesUsers setAttendanceStatus(UserAttendanceStatus attendanceStatus) {
this.attendanceStatus = attendanceStatus;
return this;
}
}
You probably have begun a transaction, and trying to begin another one without having committed or rollbacked the previous one. The idiom when using programmatic transaction demarcation is the following one:
try {
sess.getTransaction().begin();
// do some work
sess.getTransaction().commit()
}
catch (RuntimeException e) {
sess.getTransaction().rollback();
throw e;
}
This is cumbersome and error-prone, and this is one of the reasons why using EJBs or Spring to have declarative transactions is so useful.
Firstly, you should inject the hibernateProperties, hibernate.current_session_context_class,
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
</props>
</property>
then you can use getCurrentSession() to get the CurrentSession.
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
long count = (Long) session
.createQuery("select count(*) from User u where u.name = :name")
.setString("name", name).uniqueResult();
session.getTransaction().commit();
I have the same problem before. First run:
session.beginTransaction();
session.save(something);
session.getTransaction().commit();
when query something by:
session.beginTransaction();
session.query ...
the same exception is raised at second beginTranscation. I solved it by using
session.getTransaction().begin();
instead of
session.beginTransaction();
both in query and save.
What you did here :
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
is actually trying to use an open session without closing it.
It happened to me and I was facing same problem, and what I did is :
Session session = HibernateUtil.getSessionFactory().openSession();
// Hibernate bla bla bla transaction or rollback
// then always close your session :
if (session.isOpen()) {
session.close();
}
and there weren't "Hibernate Nested Transaction Not Supported Error" raised again ...
Try using finally to close your Hibernate session, like this:
try {
session.getTransaction().begin();
// YOUR CODE
session.getTransaction().commit();
} catch (RuntimeException e) {
try{
session.getTransaction().rollback();
} catch(RuntimeException rbe) {
log.error("Couldn’t roll back transaction", rbe);
}
throw e;
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
I solve this problem creating diferent sessions with
Session session = factory.openSession();
session.beginTransaction();
//your code here
session.getTransaction().commit();
this line "session.beginTransaction();" prevent multiple transactions so remove this line and try because in select query it is not neccessary but it code not works after removing this then at the end of this code add " session.rollback();".
I could solve it with the following code:
public class UserDaoImpl implements UserDao {
Session session = null;
public UserDaoImpl() {
this.session = HibernateUtil.getSessionFactory().openSession();
}
#Override
public List<TblUsuario> getAllUsers() {
List<TblUsuario> listUsuarios = null;
try {
org.hibernate.Transaction tx = this.session.getTransaction();
Query query = this.session.createQuery("....");
listUsuarios = query.list();
} catch (Exception e) {
e.printStackTrace();
}
return listUsuarios;
}
...
}

Categories