hibernate - How to restrict other columns data getting updated while updating specific columns of a table -
how restrict columns want update in database table rather updating columns of table?
the following update remarks column
@test public void updateproject() { try { project project = new project(); project.setprojectid(234l); project.setremarks("from junit"); projectservice.update(project); } catch (exception e) { system.out.println("error" + e.getmessage()); e.printstacktrace(); } }
when execute above updated other column in table, consequently makes other column values null.
how can resolve issue?
daoimpl code
@override public void update(project project) { entitymanager.merge(project); entitymanager.flush(); }
update 1 modified code
@test public void updateproject() { try { project project = new project(); project = projectservice.load(234l); project.setremarks("from junit"); projectservice.update(project); } catch (exception e) { system.out.println("error" + e.getmessage()); e.printstacktrace(); } }
in code you're merging new object null
fields except remarks
object persistent in db. that's not right way: hibernate
reference manual:
a straightforward way update state of entity instance find() it, , manipulate directly, while persistence context open: modifying persistent objects
if need modify persistent object, first have load it, edit fields need update , save it.
so, load project
entity db , update fields need , save()
it. save()
isn't necessary hibernate
checks object modified , automatically saves it.
@test public void updateproject() { try { // load project entity db using it's id 234l project.setremarks("from junit"); projectservice.save(project); } catch (exception e) { system.out.println("error" + e.getmessage()); e.printstacktrace(); } }
here's how load object.
in dao
need method load object, example:
@override public project load(long id) { return entitymanager.find(project.class, id); }
Comments
Post a Comment