I want to remove an object gives the following error:
javax.ejb.EJBException: java.lang.IllegalArgumentException: Removing a
detached instance.
My code:
public void remover(MensagemContato param) {
PersistenciaMensagemContato pParam = new PersistenciaMensagemContato();
pParam.delete(param);
pParam.close();
}
Has anyone experienced this problem in a simple deletion of an object using hibernate?
Thanks!
Debora
There is no ID specified in your PersistenciaMensagemContato entity. How will Hibernate know which reference to delete?
You cannot delete an entity that does'nt come from database.
You can only delete entities with ID values.
This is a good tutorial.... http://www.tutorialspoint.com/hibernate/hibernate_examples.htm
public void deleteEmployee (Integer EmployeeID){
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Employee employee =
(Employee) session.get(Employee.class, EmployeeID);
session.delete(employee);
tx.commit();
} catch (HibernateException e) {
if (tx != null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
Related
I'm trying to delete the 2 rows(1 in each table) with the same id, in my service class, the breweries object is being created with the id fine but when the BreweriesGeocode object is trying to be created the BreweriesGeocode object brakes out of the try and brings me to my error.jsp page.
The line of code that causes it to break is
bg = em.createNamedQuery("BreweriesGeocode.findById", BreweriesGeocode.class)
.setParameter("id", (id))
.getSingleResult();
the code for the entire method of deleteAnBrewery in BreweriesService.java is
public void deleteAnBrewery(int id) {
EntityManager em = DBUtil.getEMF().createEntityManager();
EntityTransaction trans = em.getTransaction();
Breweries b = null;
BreweriesGeocode bg = null;
try {
b = em.createNamedQuery("Breweries.findById", Breweries.class)
.setParameter("id", (id))
.getSingleResult();
bg = em.createNamedQuery("BreweriesGeocode.findById", BreweriesGeocode.class)
.setParameter("id", (id))
.getSingleResult();
trans.begin();
em.remove(em.merge(b));
em.remove(em.merge(bg));
trans.commit();
} catch (Exception ex) {
System.out.println("Error in getting property details: " + ex);
} finally {
em.clear();
em.close();
}
}
I am not getting any error in the terminal
I didn't set the objects to null outside the try, I don't know if that was the fix because I wouldn't think that would make a difference, the only other change was turning my Netbeans off and on again, this is not a reliable solution
public void deleteAnBrewery(int id) {
EntityManager em = DBUtil.getEMF().createEntityManager();
EntityTransaction trans = em.getTransaction();
try {
Breweries b = em.createNamedQuery("Breweries.findById", Breweries.class)
.setParameter("id", (id))
.getSingleResult();
BreweriesGeocode bg = em.createNamedQuery("BreweriesGeocode.findById", BreweriesGeocode.class)
.setParameter("id", (id))
.getSingleResult();
trans.begin();
em.remove(em.merge(b));
em.remove(em.merge(bg));
trans.commit();
} catch (Exception ex) {
System.out.println("Error in getting property details: " + ex);
} finally {
em.clear();
em.close();
}
}
I want to know is transaction applicable to document deletion with database query execution?I am new in hibernate query transaction.I want to delete a document details from the database table and at the same time particular document must be delete from the document.If there is no deletion takes place in document deletion, then does not occur the database value deletion wise versa.I think this can be done using transaction.Is this applicable?Or Is there any solution to my problem?I try with transaction code.But it shows Transaction not successfully started Exception.
Thank you
In my DAOHibernateImplimentation class
getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(final Session session)throws HibernateException, java.sql.SQLException {
Transaction tx = null;
int deleteStatus=0;
try {
tx = session.beginTransaction();
final String deleteQuery = "delete from tablename where name='"+name+"'";
deleteStatus = (Integer)getHibernateTemplate().execute(new HibernateCallback(){
public Object doInHibernate(final Session session) throws HibernateException, java.sql.SQLException
{
Query query = session.createSQLQuery(deleteQuery);
return query.executeUpdate();
}
});
if(deleteStatus>0){
file.delete();
}
tx.commit();
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
}
return deleteStatus;
}
});
Exception is:
17:09:30,447 ERROR [STDERR] org.springframework.transaction.TransactionSystemException: Could not commit Hibernate transaction; nested exception is org.hibernate.TransactionException: Transaction not successfully started
17:09:30,447 ERROR [STDERR] at org.springframework.orm.hibernate3.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:562)
17:09:30,447 ERROR [STDERR] at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:662)
17:09:30,447 ERROR [STDERR] at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:632)
Try with TransactionTemplate
TransactionTemplate transactionTemplate=new TransactionTemplate();
transactionTemplate.execute(new TransactionCallback() {
#Override
public Object doInTransaction(TransactionStatus status) {
int deleteStatus = 0;
try {
final String deleteQuery = "delete from tablename where name='" + name + "'";
deleteStatus = (Integer) getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(final Session session) throws HibernateException, java.sql.SQLException {
Query query = session.createSQLQuery(deleteQuery);
return query.executeUpdate();
}
});
if (deleteStatus > 0) {
file.delete();
}
} catch (Exception e) {
e.printStackTrace();
}
return deleteStatus;
}
});
It seems like the getHibernateTemplate().execute ... is not executed in the Transaction. Like described here Hibernate transaction not successfully started there might be nothing to commit. I suggest you to remove the HibernateCallback and just directly execute the query.
Edit. Like this!
getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(final Session session)throws HibernateException, java.sql.SQLException {
Transaction tx = null;
int deleteStatus=0;
try {
tx = session.beginTransaction();
final String deleteQuery = "delete from tablename where name='"+name+"'";
Query query = session.createSQLQuery(deleteQuery);
deleteStatus = query.executeUpdate();
if(deleteStatus>0){
boolean deleted = file.delete();
if(!deleted)
throw new IOException("Error deleting");
}
tx.commit();
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
}
return deleteStatus;
});
You need to check the return value of the file.delete() call. (See JavaDoc)
Why session object's delete method is not working in GenericDAOImpl.java, neither its giving any exception nor its showing any output. All other methods working fine expect public void delete(T object), Please help me, Sorry if i asked this question in wrong way.
public class GenericDAOImpl<T> implements IGenericDAO<T> {
private SessionFactory sessionFactory;
public GenericDAOImpl(Class<T> cl, SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
if (sessionFactory == null)
throw new RuntimeException("Session factory is null!!!");
}
#Override
public T get(Class<T> cl, Long id) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
#SuppressWarnings("unchecked")
T element = (T) session.get(cl, id);
session.getTransaction().commit();
return element;
}
#Override
public T get(Class<T> cl, Serializable obj) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
#SuppressWarnings("unchecked")
T element = (T) session.get(cl, obj);
session.getTransaction().commit();
return element;
}
#Override
public T save(T object) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
session.save(object);
session.getTransaction().commit();
return object;
}
#Override
public void update(T object) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
session.update(object);
session.getTransaction().commit();
}
#Override
public void delete(T object) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
session.delete(object);
session.getTransaction().commit();
}
#SuppressWarnings("unchecked")
#Override
public T findUniqueByQuery(String hsql, Map<String, Object> params) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Query query = session.createQuery(hsql);
if (params != null) {
for (String i : params.keySet()) {
query.setParameter(i, params.get(i));
}
}
return (T) query.uniqueResult();
}
#SuppressWarnings("unchecked")
#Override
public List<T> query(String hsql, Map<String, Object> params) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Query query = session.createQuery(hsql);
if (params != null) {
for (String i : params.keySet()) {
query.setParameter(i, params.get(i));
}
}
List<T> result = null;
if ((hsql.toUpperCase().indexOf("DELETE") == -1)
&& (hsql.toUpperCase().indexOf("UPDATE") == -1)
&& (hsql.toUpperCase().indexOf("INSERT") == -1)) {
result = query.list();
} else {
}
session.getTransaction().commit();
return result;
}
}
As investigated in comments, you are facing
org.hibernate.TransactionException: nested transactions not supported exception
This is happening because you began transaction and never committed or rollbacked upon an exception.
I can see one of it's case in your code. See your code below
#SuppressWarnings("unchecked")
#Override
public T findUniqueByQuery(String hsql, Map<String, Object> params) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Query query = session.createQuery(hsql);
if (params != null) {
for (String i : params.keySet()) {
query.setParameter(i, params.get(i));
}
}
return (T) query.uniqueResult();
}
See, you began and never committed a transaction. Like wise check all other places in your project.
I have the same problem. Although I was not using transaction at all. I was using namedQuery like this :
Query query = session.getNamedQuery(EmployeeNQ.DELETE_EMPLOYEES);
int rows = query.executeUpdate();
session.close();
It was returning 2 rows but the database still had all the records. Then wrap up the above code with this :
Transaction transaction = session.beginTransaction();
Query query = session.getNamedQuery(EmployeeNQ.DELETE_EMPLOYEES);
int rows = query.executeUpdate();
transaction.commit();
session.close();
Then it started working fine. I was using SQL server. But I think if we use h2 above code (without transaction) will also work fine.
org.hibernate.TransactionException: nested transactions not supported exception
Most probably you're not closing your session after an update or insert, and then you're doing the delete.
i have to update some rows in database using Hibernate and Struts2:
the method DAO where i put the requete is:
public void modifier(String cond) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
try{Query query = session.createQuery("Update Processus set selectionne = '1' where"+cond );
// query.setString("idproc",idprocessus);
// query.setLong("idsi", identifiantsi);
}catch(HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
}
session.getTransaction().commit();
}
In my action class where i call the DAO, i specify the cond:
public String update(){
cond="id_processus="+checked;
procdao.modifier(cond);
return SUCCESS;
}
can u help me it doens't show any error in the console but the row's value don't change!!!!
Following code could be helpful: Processus Table name selectionne and idproc are column name
You need to execute the query
To check the number of updated rows.
public Boolean modifier(String cond) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Boolean returnValue = false;
try {
Query query = session.createQuery("Update Processus set selectionne = '1' where idproc=:cond");
query.setString("cond", cond);
int noOfUpdate = query.executeUpdate();
returnValue = (noOfUpdate > 0);
} catch (HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
}
session.getTransaction().commit();
return returnValue;
}
I am trying to run an update query which would look like this in sql:
update studentMaster set sess_status = 'G' where ACADEM_YEAR = COURSE_YEAR;
I am trying to re-create the query using Criteria like this:
public void updateSessionStatus() {
Session sess = factory.openSession();
Transaction tx = null;
try {
tx = sess.beginTransaction();
Criteria crit = sess.createCriteria(CollegeStudentsMaster.class);
crit.add(Restrictions.eqProperty("academicYear", "courseYears"));
CollegeStudentsMaster e = (CollegeStudentsMaster) crit.uniqueResult();
e.setSessionStatus("G");
sess.saveOrUpdate(e);
tx.commit();
} catch (HibernateException asd) {
if (tx != null) {
tx.rollback();
}
log.debug(asd.getMessage());
} finally {
sess.close();
}
}
This is not working because the rows which meet this Criteria are many, my unique result is the problem here I guess.
How can I convert this into an update for all the rows that meet the Criteria. I do not want to use HQL query, I am rather doing it with Criteria.
public void updateSessionStatus() {
Session sess = factory.openSession();
Transaction tx = null;
try {
tx = sess.beginTransaction();
Criteria crit = sess.createCriteria(CollegeStudentsMaster.class);
crit.add(Restrictions.eqProperty("academicYear", "courseYears"));
// Here is updated code
ScrollableResults items = crit.scroll();
int count=0;
while ( items.next() ) {
CollegeStudentsMaster e = (CollegeStudentsMaster)items.get(0);
e.setSessionStatus("G");
sess.saveOrUpdate(e);
if ( ++count % 100 == 0 ) {
sess.flush();
sess.clear();
}
}
tx.commit();
} catch (HibernateException asd) {
if (tx != null) {
tx.rollback();
}
log.debug(asd.getMessage());
} finally {
sess.close();
}
}
It is always suggested that execute bulk operations very close to database and we do not need keep updated object in session unless they are required, Hence try to avoid load objects in session while executing bulk operations.