【发布时间】:2019-07-04 09:48:15
【问题描述】:
我有一张桌子products。在这张表中,我需要带有约束的is_active - only one row with the same type can be true.
我有通过检查保存新的Product 的服务:
@Service
public class ProductServiceImpl implements ProductService {
private final ProductRepository productRepository;
public ProductServiceImpl(ProductRepository productRepository) {
this.productRepository = productRepository;
}
@Override
public void save(Product product) {
Product productInDb = productRepository.findOneByTypeAndIsActive(product.getType());
if (productInDb != null)
throw new AlreadyActiveException();
product.setActive(true);
productRepository.saveAndFlush(product);
}
}
当我在几个线程中调用 save 方法并尝试检查活动产品时 - 在两个线程中 findOneByTypeAndIsActive 方法返回 productInDb is null 因为我在表中没有活动产品。
在每个线程中我设置product.setActive(true); 并尝试保存在数据库中。
如果我在 DB 中没有约束 - 我将两个产品都保存在 is_active = true 状态并且未执行此检查:
if (productInDb != null)
throw new AlreadyActiveException();
我的问题 - 我可以在不在数据库中添加约束的情况下解决这个问题吗? 而且上面的检查也没用?
【问题讨论】:
标签: java multithreading hibernate jpa spring-data-jpa