I am trying to update a row by using its primary key, the issue is that Hibernate updates entire row and since I have not passed values for any other attributes (For Ex : Attributes are empid, name salary and address. I will pass empid=1 and name to be updated. But it will set NULL to other 2 values i.e. address and salary) it assigns NULL to them. I want to Update only selective attributes;
I tried using saveOrUpdate but that too is either entering new or updating same row with NULL values. Is there any other solutions???
CodePudding user response:
I figured the following works. The code below is the update method in my execution file which is called.
public void update(int empid,String name) {
Session session = sc.openSession();
Transaction t = session.beginTransaction();
Query q = session.createQuery("from employee");
List<?> l = q.getResultList();
Iterator<?> it = l.iterator();
employee e1 = (employee) it.next();
String Address;
int Salary;
Salary=e1.getSalary();
Address=e1.getAddress().toString();
session.evict(e1);
employee e2=new employee();
e2.setEmpid(empid);
e2.setName(name);
e2.setAddress(Address);
e2.setSalary(Salary);;
session.saveOrUpdate(e2);
t.commit();
}
CodePudding user response:
If you can use hibernate, why don't you can use JPA?
var entity = repo.getById( id );
entity.setValue( value );
repo.save(); // or repo.saveAndFlush();
CodePudding user response:
Try use the native sql to update
Session session = sessionFactory.openSession();
Transaction t = session.beginTransaction();
Query query = session.createQuery("update employee e set e.name = 'newvalue' where e = 1");
query.executeUpdate();
t.commit();
I agree with Jan Tibar
said that Jpa is more convenient than hibernate