问题描述
我在我的所有JPA域类中都在其上放置了带注释的字段,其中带有@Version
,但这似乎就像是额外的模板.有没有办法通过配置解决这个问题?
TIA,奥莱(Ole)
据JPA规范告诉我们,您不能通过配置"更改@Version
批注.您可以在程序代码中使用@Version
,也可以不使用.
请参考官方 JPA规范(最终版本,JPA 2.1)在第3.4.2节(第90页)中可以找到:
但是,您可以使用继承的概念通过抽象基类仅在一个位置提供@Version
.该类的编写方式如下:
@MappedSuperclass
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class AbstractBaseEntity {
public static final long INVALID_OBJECT_ID = -42;
@Version
private int version;
@Id
@SequenceGenerator(name = "sequence-object", sequenceName = "ID_MASTER_SEQ")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequence-object")
@Column(name = "id")
protected Long objectID = INVALID_OBJECT_ID;
public final int getVersion() {
return version;
}
@Override
public long getObjectID() {
return objectID;
}
// ... maybe other methods or fields ...
}
因此,所有从AbstractPersistentEntity
继承的带@Entity
注释的子类都具有两个属性:(i)objectID
和(ii)version
.例如,类SomeClass
可以写为:
@Entity
public class SomeClass extends AbstractBaseEntity /*implements SomeInterface*/ {
// ... specific methods or fields ...
}
有关使用@MappedSuperclass
的详细信息,另请参见此答案.
希望有帮助.
I'm placing an annotated field with @Version
on it in all my JPA domain classes, however this just seems like additional boiler plate. Is there a way to get around this perhaps via configuration?
TIA,Ole
As far as the JPA specification tells us you can't change the @Version
annotation via "configuration". You either use @Version
in your program code or you don't.
Referring to the official JPA specification (final version, JPA 2.1) in Section 3.4.2 (page 90) we find:
However, you can use the concept of inheritance to provide the @Version
only in one spot via an abstract base class. This class you be written as follows:
@MappedSuperclass
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class AbstractBaseEntity {
public static final long INVALID_OBJECT_ID = -42;
@Version
private int version;
@Id
@SequenceGenerator(name = "sequence-object", sequenceName = "ID_MASTER_SEQ")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequence-object")
@Column(name = "id")
protected Long objectID = INVALID_OBJECT_ID;
public final int getVersion() {
return version;
}
@Override
public long getObjectID() {
return objectID;
}
// ... maybe other methods or fields ...
}
Thus, all your @Entity
annotated sub-classes that inherit from AbstractPersistentEntity
are provided with both properties: (i) objectID
and (ii) version
at once. For instance, class SomeClass
can be written as:
@Entity
public class SomeClass extends AbstractBaseEntity /*implements SomeInterface*/ {
// ... specific methods or fields ...
}
For details on the use of @MappedSuperclass
see also this answer.
Hope it helps.
这篇关于是否可以使用@Version替代配置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!