Update data with Struts and Hibernate - java

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

Related

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)

How to add multiple class in criteria to check a column

Here is the above code, I just want to add country class to the criteria such that if the deleteflag in country class is false, it should not fetch the states in staveprovince class:
public List<StateProvince> getAllState(Country country)throws HibernateException,ConstraintViolationException {
Session session = SessionFactoryUtil.getSessionFactory().openSession();
try {
session.beginTransaction();
Criteria criteria = session.createCriteria(StateProvince.class);
criteria.setCacheable(true);
criteria.add(Restrictions.eq("country", country));
criteria.add(Restrictions.eq("deleteFlag", false));
return criteria.list();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
session.getTransaction().commit();
session.close();
}
}
I guess country is an attribute of StateProvince of type Country, so in that case your criteria must be the following:
criteria.createCriteria("country").add(Restrictions.eq("deleteFlag", false));
public class StateProvinceDAOImpl implements StateProvinceDAO {
#SuppressWarnings("unchecked")
#Override
public List<StateProvince> getAllState(Country country)throws HibernateException,ConstraintViolationException {
Session session = SessionFactoryUtil.getSessionFactory().openSession();
try {
session.beginTransaction();
Criteria criteria = session.createCriteria(StateProvince.class,"state");
criteria.setCacheable(true);
criteria.createAlias("state.country", "country");
criteria.add(Restrictions.eqProperty("state.deleteFlag", "country.deleteFlag"));
criteria.add(Restrictions.eq("country", country));
criteria.add(Restrictions.eq("deleteFlag", false));
return criteria.list();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
session.getTransaction().commit();
session.close();
}
}
I am assuming you have Country associated in StateProvince. Please comment if this does not solve your problem.
public List<StateProvince> getAllState(Country country)throws HibernateException,ConstraintViolationException {
Session session = SessionFactoryUtil.getSessionFactory().openSession();
try {
session.beginTransaction();
Criteria criteria = session.createCriteria(StateProvince.class);
criteria.createAlias("country", "country");
criteria.setCacheable(true);
criteria.add(Restrictions.eq(deleteFlag", false));
criteria.add(Restrictions.eq("country", country));
criteria.add(Restrictions.eq("country.deleteFlag", false));
return criteria.list();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
session.getTransaction().commit();
session.close();
}
}

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.

Where can I see system.out.println message?

I have a helper class like this:
public class FtHelper {
Session session = null;
public FtHelper() {
this.session = HibernateUtil.getSessionFactory().getCurrentSession();
}
public FinancialTransactions getByBeginDate(String beginDate) {
List<FinancialTransactions> FtList = null;
try {
org.hibernate.Transaction tx = session.beginTransaction();
Query q = session.createQuery(
"from FinancialTransactions where DATE=:date")
.setParameter("date", beginDate);
FtList = (List<FinancialTransactions>) q.list();
} catch (Exception e) {
e.printStackTrace();
}
return FtList.get(0);
}
}
I add a System.out.println(beginDate); just above return, but it doesn't appear to print anything. I also used System.out.println("anytext"), but it didn't work either. Where can I see that output message in Netbeans? By the way, I get the value beginDate from my JSF.
You should be able to find the output (most of the time) in catalina.out.
Under Windows, you should be able to find it in the folder: <Tomcat Folder>\logs

Categories