ranjani murali
ranjani murali

Reputation: 121

dynamicUpdate=true in Hibernate using annotations not working

Even after using dynamicUpdate=true(for updating selective columns instead of all columns) in the entity class annotation using org.hibernate.annotations.entity(dynamicUpdate=true), hibernate is trying to update all the fields of the table and since I am having "not null" constraints on few columns, it throws exception. How to resolve this? Please help as soon as possible..

Upvotes: 2

Views: 11701

Answers (3)

Deepak Jindal
Deepak Jindal

Reputation: 1

Dynamic update works only when first we fetch value by using session.get(...) In this case suppose we have 10 columns and we want to update 5 columns then first we fetch object by using id then set new value into fetched object and it works fine More we write coding only for 5 columns and if we update one column from that 5 column then by using dynamic update query fire as shown below

Hibernate: update usermaster set name=? where user_id=?

below is my code and here i chenged only name from front end

Session session = sessionFactory.openSession();
Transaction tran = session.beginTransaction();
Usermaster obj = (Usermaster) session.get(Usermaster.class,
        usermaster.getUserId());
obj.setUsername(usermaster.getUsername());
obj.setName(usermaster.getName());
obj.setContact(usermaster.getContact());
obj.setEmail(usermaster.getEmail());
obj.setUserStatus(usermaster.getUserStatus());
obj.setUserType(usermaster.getUserType());
session.update(obj);

Upvotes: 0

i_v_harish
i_v_harish

Reputation: 161

Try this,

@org.hibernate.annotations.Entity(dynamicUpdate = true, selectBeforeUpdate = true)

Upvotes: 3

gkamal
gkamal

Reputation: 21000

For dynamic update to work you should fetch the object form hibernate first and then change the fields.

p = session.get(Person.class,1);
p.setFirstName("Kamal");

This will result in a query that will only update the first_name columnn.

The following doesn't work. It will issue an update query with all other columns set to null.

p = new Person()
p.setId(1)
p.setFirstName("Kamal")
session.update(p)

If you want to update only certain columns you can use the update HQL command. This is not recommended - as it by passes the cache. The correct approach is the one outlined above, load the object and then change the fields that need to be changed.

Upvotes: 4

Related Questions