JPA中的空版本字段? [英] Null Version fields in JPA?
问题描述
http://docs.oracle.com/中没有任何内容javaee / 6 / api / javax / persistence / Version.html 表示它不能为空。
运行后
import javax.validation.Validation;
import javax.validation.Validator;
import org.junit.Test;
导入static org.junit.Assert.assertFalse;
public class Test
{
@Test
public void test()
{
//使用Hibernate Validator 4.1.0.Final ...
Validator validator = Validation.buildDefaultValidatorFactory()。getValidator();
assertFalse(validator.validate(new Foo())。isEmpty()); //为什么这会失败?
其中Foo.class只是简单的
import javax.persistence.Entity;
import javax.persistence.Version;
@Entity
public class Foo
{
@版本
private final Integer version = null;
}
测试失败并且未报告任何@Version验证错误。
那么这是否意味着@ Version-annotated字段可以为空?
@版本只是定义了一个特定的字段用于乐观锁定。它不影响数据库本身的列或验证。因此,如果您想强制使用非空值,则必须使用其他注释。
如果将版本字段保留为空,您将在尝试执行更新时收到异常。
Nothing in http://docs.oracle.com/javaee/6/api/javax/persistence/Version.html says it cannot be null.
After running
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??
}
}
where Foo.class is simply
import javax.persistence.Entity;
import javax.persistence.Version;
@Entity
public class Foo
{
@Version
private final Integer version = null;
}
the test fails and no @Version validation errors are reported.
So does this mean @Version-annotated fields can be null?
@Version just defines that a particular field is used for optimistic locking. It does not affect the column in DB itself nor the validation. So if you want to enforce not null values you have to use other annotations.
If you leave the version field as null you will get an exception while trying to perform update.
这篇关于JPA中的空版本字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!