选择一个列表,并根据某个字段逐个更新记录。如何避免重复更新?
问题描述:
根据字段值逐个选择列表并更新记录。如何避免重复更新和插入?选择一个列表,并根据某个字段逐个更新记录。如何避免重复更新?
public void takeOrder(String currentUser){
String sql = "select * from customer where take_status is null limit 30";
List<Customer> customerList = customerDao.findUnTakeCustomer(sql);
for(Customer cust : customerList){
if(cust.getEntryId > 3){
cust.setTakeStatus(1);
update(cust);
Sd sd = new Sd();
sd.setUser(currentUser);
sd.setCust(cust);
sd.setTakeTime(new Date());
sdDao.save(sd);
}
}
}
如果两个用户在同一时间采取秩序,customerList也许有相同的记录,然后重复记录将被插入到表SD,和客户记录将被更新两次!
如何避免这种情况?
答
在你的mysql中使用主键。
create table tablename(
yourPrimaryKey int(10),
otherColumns varchar(10),
primary key(yourPrimaryKey)
);
主键将成为您每次交易的唯一代码。就像任何便利店的收据号码一样
是的!如果我将SD中的customer_id设置为唯一,它就可以工作。但为了与历史数据和逻辑兼容,我无法做到这一点!你知道一些其他的解决方案,只是通过使用java代码,而不是数据库约束吗? – footoss
@footoss你会请网站的历史数据和逻辑的例子吗?也许你没有让你的主主键父其它表列.. 例如: 你已经收到表格( receipt_no INT(10) –
@footoss请你的网站是什么历史数据和逻辑的例子吗? 。也许üdidnt让你的主主键父其它表列 例如: 你有 创建表回执( receipt_no INT(10), 主键(receipt_no)); 创建表receipt_info( receipt_no int(10), items varchar(50), 主键(receipt_no)); 看着这个例子,你有2票receipt_no。父母将在桌面收据中。更好的外键将receipt_info.receipt_no键入receipt.receipt_no –