【问题标题】:Null Version fields in JPA?JPA中的空版本字段?
【发布时间】:2013-04-17 11:22:54
【问题描述】:

http://docs.oracle.com/javaee/6/api/javax/persistence/Version.html 中没有任何内容表明它不能为空。

运行后

import javax.validation.Validation;
import javax.validation.Validator;

import org.junit.Test;

import static org.junit.Assert.assertFalse;

public class Test
{
    @Test
    public void test()
    {
        //Using Hibernate Validator 4.1.0.Final...
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        assertFalse(validator.validate(new Foo()).isEmpty()); //why does this fail??
    }
}

Foo.class 是简单的

import javax.persistence.Entity;
import javax.persistence.Version;

@Entity 
public class Foo
{
    @Version
    private final Integer version = null;
}

测试失败,没有报告@Version 验证错误。

这是否意味着@Version 注释的字段可以为空?

【问题讨论】:

    标签: java hibernate jpa version bean-validation


    【解决方案1】:

    @Version 只是定义了一个特定的字段用于乐观锁定。它不会影响数据库本身的列,也不会影响验证。因此,如果您想强制执行非空值,则必须使用其他注释。

    如果您将版本字段保留为 null,您将在尝试执行更新时遇到异常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-11
      • 2014-07-06
      • 2014-11-20
      • 2021-05-13
      • 2016-08-13
      相关资源
      最近更新 更多