对OneToMany关系的乐观锁定

时间:2015-01-15 13:06:05

标签: java hibernate transactions one-to-many optimistic-locking

我有一对多的分类 - 产品关系:

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
....

}

我想防止丢失修改,所以我定义了一个版本机制(并发控制),如上所述。

但是当我想保存我的父实体(Category)时,我收到以下错误:

  

无法执行声明; SQL [不适用];约束[JOHN.SYS_C0090239];嵌套异常是   org.hibernate.exception.ConstraintViolationException:不能   执行声明

这是我的Action,service和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;
}

1 个答案:

答案 0 :(得分:0)

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

相关问题