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;
}
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;
...
}
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;
}
精彩评论