How to Update a database row - java

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).

Related

Struts2 + Hibernate query result is empty

Im trying to collect the result from the query but the list is empty when I check the log in my console. The login action works perfectly but obtain the query result is somewhat not happening. I also used size() to check but it also brings a zero size. What am I missing here
See my dao class:
UserDAO.java
public User userLogin(String email, String password) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
User userinfo = new User();
try {
String hql = "select * from user where email =:email and password =:password";
SQLQuery query = session.createSQLQuery(hql);
query.addEntity(User.class);
query.setParameter("email", email);
query.setParameter("password", password);
List rows = query.list();
System.out.println("Total Number Of Records : " + rows.size());
Iterator myItr = rows.iterator();
while (myItr.hasNext()) {
Object ui = (Object) myItr.next();
userinfo = (User) ui;
System.out.println("Username : " + userinfo.getUsername());
}
if (userinfo != null) {
System.out.println("User Retrieved from DB::" + userinfo);
}
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
// close your session
session.close();
}
return userinfo;
}
Try using a Query hibernate and use uniqueResult():
String hql = "from user where email =:email and password =:password";
Query query = session.createQuery(hql);
query.setParameter("email", email);
query.setParameter("password", password);
User userinfo = (User) query.uniqueResult();

Delete all rows of Table in Hibernate 4.2.21

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

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

Cannot add or update a child row on the sql

Cannot add or update a child row: a foreign key constraint fails (dbprojeto.avaliacao, CONSTRAINT fk_cliente_avaliacao FOREIGN KEY (cliente) REFERENCES cliente (idcliente) ON DELETE NO ACTION ON UPDATE NO ACTION)
I got the above error message when trying to insert some datas in the Data Base. The table has 5 fields, 2 of them are foreign key though. I was told that I have to recover the ids(foreign keys) first so that I could insert correctly. One of the ID's that has to be caught is on the session which is in the JSP page, when users are already logged in. Guess there's nothing wrong with the DAO class once that debug project shows me that is all correct. Might be something with the Servlet I certainly think.
SERVLET
try {
Avaliacao avaliacao = new Avaliacao();
Prestador prestador = new Prestador();
Cliente cliente = new Cliente();
avaliacao.prestador = new Prestador();
AvaliacaoDAO dao = new AvaliacaoDAO();
avaliacao.setNota(Integer.parseInt(request.getParameter("nota")));
avaliacao.setComentario(request.getParameter("comentario"));
HttpSession session = request.getSession(true);
avaliacao.cliente = (Cliente) session.getAttribute("cliente");
avaliacao.cliente.setIdcliente(avaliacao.cliente.getIdcliente());
dao.inserirAvaliacao(avaliacao);
avaliacao.prestador.setIdprestador(PrestadorDAO.retornarId());
request.setAttribute("msg", "Gravado com sucesso!");
request.getRequestDispatcher("cadastrado.html").forward(request, response);
DAO Insert method
public boolean inserirAvaliacao(Avaliacao avaliacao) throws SQLException {
try {
Connection conexao = Conexao.getConexao();
Statement stmt = conexao.createStatement();
String sql = "insert into avaliacao(idavaliacao, nota, comentario, cliente, prestador)values(?,?,?,?,?)";
PreparedStatement pstmt = conexao.prepareCall(sql);
avaliacao.cliente = new Cliente();
avaliacao.prestador = new Prestador();
pstmt.setInt(1, avaliacao.getIdavaliacao());
pstmt.setInt(2, avaliacao.getNota());
pstmt.setString(3, avaliacao.getComentario());
pstmt.setInt(4, avaliacao.cliente.getIdcliente());
pstmt.setInt(5, avaliacao.prestador.getIdprestador());
pstmt.execute();
conexao.close();
return true;
} catch (ClassNotFoundException ex) {
System.out.println(ex);
return false;
} catch (SQLException sql) {
System.out.println(sql);
return false;
}
}
Session in the JSP
<%
Cliente cliente = (Cliente) session.getAttribute("cliente");
if (cliente == null) {
cliente = (Cliente) session.getAttribute("cliente");
}
%>
I would say avaliacao.cliente.getIdcliente()); returns a value that does not exist in your cliente database table.

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