NHibernate的可能无法更新你上面显示的方式mail_subscriptions
但它可以使用批量查询,做到在单次往返到数据库。
此示例考虑Subscriptions
映射为一个Component
使用HasMany
虽然大致相同的技术可以如果映射只是一个普通的HasMany
使用。我还假设每个用户已经在mail_subscriptions
表中为subscribed
的每个邮寄列表设置为false
。
public class User{
public virtual string Id {get; set;}
public virtual IList<MailSubscription> Subscriptions {get; set;}
}
public class MailSubscription{
public virtual int ListId {get; set;}
public virtual bool Subscribed {get; set;}
}
public void UpdateSubscriptions(string userid, int[] mailingListIds){
var user = session.Get<User>(userid);
foreach(var sub in
user.Subscriptions.Where(x=> mailingListIds.Contains(x.ListId))){
sub.Subscribed=true;
}
session.Update(user);
}
现在当工作单元完成后,您应该看到像这样产生的SQL作为单次往返数据库发送。
update mail_subscriptions set subscribed=true where user_id='me' and listid=21
update mail_subscriptions set subscribed=true where user_id='me' and listid=14
update mail_subscriptions set subscribed=true where user_id='me' and listid=15
update mail_subscriptions set subscribed=true where user_id='me' and listid=19