Delete all rows of Table in Hibernate 4.2.21 - java

I'm working with oracle 12c, and Hibernate 4.2.21, I want to delete two tables in telationship OnetoMany.
My method is with delete From "Table":
public void deleteAllRecords() {
Session session = HibernateSessionFactory.getSessionFactory()
.openSession();
try {
session.beginTransaction();
// String hql = String.format("TRUNCATE table MapField");
// Query query = session.createQuery(hql);
// query.executeUpdate();
Query q1 = session.createQuery ("DELETE FROM MapField");
int deleted = q1.executeUpdate ();
Query q2 = session.createQuery ("DELETE FROM MapRecord");
int deleted = q2.executeUpdate ();
} catch (Exception e) {
logger.error("Error :" + e);
session.getTransaction().rollback();
} finally {
session.close();
}
When I execute this, I dond't receive none Error , only this:
INFO [stdout] (ServerService Thread Pool -- 60) Hibernate: delete from MapField
But when I go to check the Tables in the Db, the rows still are here..

try to commit your transaction after q2.executeUpdate();
session.getTransaction().commit();

Related

Trying to delete 2 rows in database using JPA. One object is created from id but other isnt

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();
}
}

How to Update a database row

Basically I want to check if the user exists I want to update with the new object settings. I got stuck on the update clause. How can I do this??
I want to update ALL the data from settings not only user string.
Settings settings = new Settings();
settings.setBaselineImg(baselineImg);
settings.setGitlabUrl(gitlabUrl);
settings.setGitlabToken(gitlabToken);
settings.setProfileProject(profileProject);
settings.setWebCSRProject(webCSRProject);
settings.setWebAdminProject(webAdminProject);
settings.setWebClientProject(webClientProject);
settings.setDockerHostname(dockerHostname);
settings.setDockerIP(dockerIP);
settings.setDockerPort(dockerPort);
settings.setUser(user);
//if settings for this user already exist just Update them
CheckIfSettingsForUserExist(user,settings);
//else Add to database
ManageDatabase.AddToDatabase(settings);
}
private static void CheckIfSettingsForUserExist(String user, Settings settings) {
SessionFactory factory = HibernateUtil.GetSessionFactory();
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
try {
String hql = "FROM Settings s WHERE s.user = :user";
Query query = session.createQuery(hql);
query.setParameter("user",user);
//If settings for user already exist
if(query.list().size() > 0)
{
//Update
String hqlUpdate = "UPDATE FROM Settings";
Query queryUpdate = session.createQuery(hqlUpdate);
queryUpdate.setParameter("user", user);
}
tx.commit();
} catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
Query query = session.createQuery("update settings set user = :user");
query.setParameter("user",user);
int result = query.executeUpdate();
I hope there is going to be a where clause in the query because this update will update all the rows to new user (string value).

Want to delete database value and document from folder in a single hibernate transaction

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)

Update data with Struts and Hibernate

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;
}

Update multiple rows using hibernate Criteria

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.

Categories