rottmanj
rottmanj

Reputation: 531

Updating Multiple Rows - Hibernate

In my addresses table, I have an field named isPrimary. For each address assigned to a user, the user can only have one address as a primary.

I have the method below that I am trying to fix. If a new address is to be created and has the attribute isPrimary set to true, I need to update all of the users existing addresses and set isPrimary to false.

When this method is called and an existing record has the attribute set to true. The return I get back is null.

Is it even possible to do this? I would use a trigger, but MySql does not support triggers acting on the table they are inserting/updating on.

This is my save method

@Override 
public UserAddress save(UserAddress obj) throws UserException
{
    if(obj.getIsPrimary())
    {
        List<UserAddress> addressList = template.find("FROM UserAddress WHERE UserID = ?", obj.getUserAccount().getUserId());

        for(Iterator<UserAddress> i = addressList.iterator(); i.hasNext();)
        {
            i.next().setIsPrimary(false);

            template.update(i.next());
        }           
    }

    template.saveOrUpdate(obj);

    return obj;
}

Upvotes: 0

Views: 7089

Answers (2)

Talha Ahmed Khan
Talha Ahmed Khan

Reputation: 15473

Please make few changes in your method. You are calling i.next() twice in the for loop. i.next() get the next element in the list.

@Override 
public UserAddress save(UserAddress obj) throws UserException
{
    if(obj.getIsPrimary())
    {
        List<UserAddress> addressList = template.find("FROM UserAddress WHERE UserID = ?", obj.getUserAccount().getUserId());

        for( UserAddress add : addressList )
        {
            add.setIsPrimary(false);

            template.update(add);
        }           
    }

    template.saveOrUpdate(obj);

    return obj;
}

Upvotes: 1

Maurice Perry
Maurice Perry

Reputation: 32831

The issue in your code is that you are calling next() twice in the loop. This should work:

    for(UserAddress> addr: addressList)
    {
        addr.setIsPrimary(false);

        template.update(addr);
    }           

Personnally, I would have made a User class such as:

class User {
   private List<UserAddress> addresses = new ArrayList<UserAddress>();
   private UserAddress primaryAddress;
...
}

Upvotes: 1

Related Questions