Delete by id in hibernate

Example for openSession


public void deleteMyObjectById(Context context,
		int myObjectId) {

	Session session = null;
	try {
		session = this.sessionFactory.openSession();
		session.beginTransaction();
		MyObject protocolEditStep = (MyObject)session.load(MyObject.class,myObjectId);
		session.delete(protocolEditStep);
		session.getTransaction().commit();
	} catch (Exception e) {
		rollbackQuietly(session);
		session.close();
		logger.error("exception while delete",e);
		throw new IllegalStateException(e);
	} finally{
		closeQuietly(session);
	}
}

private void rollbackQuietly(Session session) {
	if (session != null) {
		try {
			session.getTransaction().rollback();
		} catch (Exception e) {
			logger.error(e);
		}
	}
}
// the exception what got it here has the precedence so preserving that exception by closing connection quietly
private void closeQuietly(Session session) {
	if (session != null) {
		try {
			session.close();
		} catch (Exception e) {
			try {
				session.disconnect();
			} catch (Exception e1) {
				logger.error(e1);
			}
		}

	}
}

 

Example for getCurrentSession


Session session = this.sessionFactory.getCurrentSession();
MyObject protocolEditStep = (MyObject)session.load(MyObject.class,myObjectId);
session.delete(protocolEditStep);
session.flush();

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.