使用SessionCustomizer为所有JPA实体分配序列
我正在尝试使用一个使用SessionCustomizer为所有JPA实体分配序列,jpa,eclipselink,sequence,Jpa,Eclipselink,Sequence,我正在尝试使用一个SessionCustomizer自动生成EclipseLink中的序列,该序列按照特殊的命名约定已经存在于数据库中。例如,名为Item的实体映射到名为ITEMS的表,该表具有四个字母的别名Item和名为Item\u ID\u SEQ的数据库序列,以生成唯一ID 我使用注释作为标记来保存实体类上的别名,因为我们也将其用于其他目的: package jpa.namingsupport; // imports omitted @Target(TYPE) @Retention(R
SessionCustomizer
自动生成EclipseLink中的序列,该序列按照特殊的命名约定已经存在于数据库中。例如,名为Item
的实体映射到名为ITEMS
的表,该表具有四个字母的别名Item
和名为Item\u ID\u SEQ
的数据库序列,以生成唯一ID
我使用注释作为标记来保存实体类上的别名,因为我们也将其用于其他目的:
package jpa.namingsupport;
// imports omitted
@Target(TYPE)
@Retention(RUNTIME)
public @interface Alias {
String name();
}
实体如下所示:
package jpa.entities;
// imports omitted
@Entity
@Table(name = "ITEMS")
@Alias(name = "ITEM")
public class Item {
@Id
private Long id;
@Version
private Long version;
private String name;
// setters and getters omitted
}
使用在启动时正确注册并验证运行的SessionCustomizer创建序列并将其添加到实体:
package jpa.namingsupport;
// imports omitted
public class AliasCustomizer implements SessionCustomizer {
@Override
public void customize(Session session) throws Exception {
Map<Class, ClassDescriptor> entities = session.getDescriptors();
for (Class entity : entities.keySet()) {
customizeSequence(aliasNameFor(entity), entities.get(entity), session);
}
}
private String aliasNameFor(Class entity) {
Alias alias = (Alias) entity.getAnnotation(Alias.class);
return alias.name();
}
private void customizeSequence(String alias, ClassDescriptor descriptor, Session session) {
NativeSequence sequence = new NativeSequence(underscores(alias, "ID", "SEQ"), 1);
session.getLogin().addSequence(sequence);
descriptor.setSequenceNumberName(sequence.getName());
descriptor.setSequenceNumberField(descriptor.getPrimaryKeyFields().get(0));
descriptor.setSequence(sequence);
}
private String underscores(String... parts) {
return StringUtils.arrayToDelimitedString(parts, "_");
}
}
我的代码中缺少了什么提示和想法?我看到的是,在生成的insert语句中没有对ITEM_ID列的引用。为什么不在ID上加上@GeneratedValue(strategy=SEQUENCE,generator=“ITME_ID_SEQ”) 对于自定义程序,不要调用descriptor.setSequence(),这应该在初始化时完成
SQL希望id使用标识值,您需要为此配置表。如果您想改为使用序列,则将false传递到新的NativeSequence(name、increment、false)。H2支持标识和序列,NativeSequence默认使用标识,false表示序列。谢谢!NativeSequence构造函数上缺少的布尔参数正是我问题的解决方案。我不想将GeneratedValue注释放在id字段中,因为我要将其保留在实体的基类中。
[EL Warning]: 2013-07-14 20:32:32.571--UnitOfWork(1908148255)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.h2.jdbc.JdbcSQLException: NULL nicht zulässig für Feld "ITEM_ID"
NULL not allowed for column "ITEM_ID"; SQL statement:
INSERT INTO ITEMS (ITEM_NAME, ITEM_VERSION) VALUES (?, ?) [23502-172]