乐观锁定一对一的关系

nxowjjhe  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(399)

我有一对多类别产品关系:

public class**Category**{

    @Version
    private Integer version;

    @OneToMany(mappedBy = "category", cascade = {CascadeType.ALL})
    //@OptimisticLock(excluded = true)
    private List<Product> products
....

}

多到一边:

public class**Product**{

    @Version
    private Integer version;

    @ManyToOne
    @JoinColumn(name = "category_id")
    @ForeignKey(name = "fk_category_product")
    //@OptimisticLock(excluded = true)
    private Category category
....

}

我想防止丢失修改,所以我定义了一个版本机制(并发控制),如上所述。
但是,当我想保存父实体(类别)时,会出现以下错误:
无法执行语句;sql[不适用];约束[john.sys_c0090239];嵌套异常为org.hibernate.exception.constraintviolationexception:无法执行语句
以下是我的操作、服务和dao层:

行动

public String save() throws Exception {

        try {

            categoryManager.saveCategory(category);

        }catch (CategoryExistException e){
            List<Object> args = new ArrayList<Object>();
            args.add(category.getCategoryName());//categoryName is UNIQUE
            addActionError(getText("errors.existing.category", args));
            return INPUT;
        }

}

经理

@Override
public Category saveCategory(Category category) throws CategoryExistException{

    if (category.getVersion()==null)
    {
        // if new category, lowercase categoryId
        category.setCategoryName(category.getCategoryName().toLowerCase());
    }

    try {
        return categoryDao.saveCategory(category);
    } catch (final Exception e) {
        e.printStackTrace();
        log.warn(e.getMessage());
        throw new CategoryExistException("Category '" + category.getCategoryName() + "' already exists!");
    }
}

@Override
public Category saveCategory(Category category){

    if (log.isDebugEnabled()) {
        log.debug("category's id: " + category.getCategoryId());
    }

    getSession().saveOrUpdate(category);
    //getSession().merge(category);

    // necessary to throw a DataIntegrityViolation and catch it in CategoryManger
    getSession().flush();

    return category;
}
clj7thdc

clj7thdc1#

您的问题与乐观锁定无关。你得到一个 ConstraintViolationException ,由于sql JOHN.SYS_C0090239 约束。

相关问题