Delete by id in hibernate

Example for openSession

</p>
<p>public void deleteMyObjectById(Context context,<br />
		int myObjectId) {</p>
<p>	Session session = null;<br />
	try {<br />
		session = this.sessionFactory.openSession();<br />
		session.beginTransaction();<br />
		MyObject protocolEditStep = (MyObject)session.load(MyObject.class,myObjectId);<br />
		session.delete(protocolEditStep);<br />
		session.getTransaction().commit();<br />
	} catch (Exception e) {<br />
		rollbackQuietly(session);<br />
		session.close();<br />
		logger.error(&quot;exception while delete&quot;,e);<br />
		throw new IllegalStateException(e);<br />
	} finally{<br />
		closeQuietly(session);<br />
	}<br />
}</p>
<p>private void rollbackQuietly(Session session) {<br />
	if (session != null) {<br />
		try {<br />
			session.getTransaction().rollback();<br />
		} catch (Exception e) {<br />
			logger.error(e);<br />
		}<br />
	}<br />
}<br />
// the exception what got it here has the precedence so preserving that exception by closing connection quietly<br />
private void closeQuietly(Session session) {<br />
	if (session != null) {<br />
		try {<br />
			session.close();<br />
		} catch (Exception e) {<br />
			try {<br />
				session.disconnect();<br />
			} catch (Exception e1) {<br />
				logger.error(e1);<br />
			}<br />
		}</p>
<p>	}<br />
}<br />

 

Example for getCurrentSession

</p>
<p>Session session = this.sessionFactory.getCurrentSession();<br />
MyObject protocolEditStep = (MyObject)session.load(MyObject.class,myObjectId);<br />
session.delete(protocolEditStep);<br />
session.flush();</p>
<p>

Like this post? Don’t forget to share it!

Leave a Reply

Your email address will not be published. Required fields are marked *

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