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.
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 am using Hibernate and I have Many methods of this type:
public static void modifySchemeEvents(String schmCode, String username) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Criteria cr = session.createCriteria(SchmEventsTable.class);
cr.add(Restrictions.eq("schmCode", schmCode));
SchmEventsTable evt = (SchmEventsTable) cr.uniqueResult();
evt.setLchgUserId(username);
tx.commit();
} catch (HibernateException asd) {
log.debug(asd.getMessage());
if (tx != null) {
tx.rollback();
}
} finally {
session.close();
}
}
This updated the database with the username where schmCode is <schmCode> I am attempting to convert to generic so that I do not have to write a separate method for all updates so I have come up with this generic method:
public static <T> T getUpdateObject(Class c, Map<String, ?> params) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = null;
T value = null;
try {
tx = session.beginTransaction();
Criteria cr = session.createCriteria(c);
for (Map.Entry<String, ?> entry : params.entrySet()) {
cr.add(Restrictions.eq(entry.getKey(), entry.getValue()));
}
value = (T) cr.uniqueResult();
////How to set the values here?***
tx.commit();
} catch (HibernateException asd) {
log.debug(asd.getMessage());
if (tx != null) {
tx.commit();
}
} finally {
session.close();
}
return value;
}
I am attempting to use it this way:
Map<String, String> schemeEventMap = new HashMap();
schemeEventMap.put("schmCode", "CA201");
SchmEventsTable evt = DataOperation.getUpdateObject(SchmEventsTable.class, schemeEventMap);
evt.setLchgUserId(username);
This does not update the table like the first method. I am wondering how to pass the parameters in the generic Method Dynamically.
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).
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 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();
}
}