我正在使用带有JavaDB的EclipseLink,每次我尝试持久化一个新的用户实体时,我都会收到与新用户实体的ID字段为空相关的错误。我知道它是空的 - 这应该是因为ID字段是作为数据库中的标识生成的。还是我错了?我尝试向实体添加@GeneratedValue,但无论使用哪种生成策略,都会导致错误。我也看过这里,这里和这里,但这些问题似乎与我的问题并不完全相关。以下异常始终在调用 EntityManager.persist(user( 时发生。
我还尝试删除@NotNull和@GeneratedValue,奇怪的是,它通过了持久调用 - 但只是在提交时失败。据我所知,我已经把一切都做好了。所以问题是:为什么此应用程序无法添加新用户,我需要做什么来修复它?
用户实体:
@Entity(name = "User")
@Table(name = "USERS")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
@Column(name = "IDENTIFIER", nullable = false,unique = true)
private Long identifier;
// class shortened for brevity
}
对应于此 SQL 脚本:
create table "USERSDBADMIN".USERS
(
IDENTIFIER BIGINT not null primary key GENERATED ALWAYS AS IDENTITY
(START WITH 0, INCREMENT BY 1),
USERNAME VARCHAR(50) not null,
EMAIL VARCHAR(150) not null,
LASTLOGIN DATE default NULL
);
用户创建方法(从 JPA 控制器(:
public void create(User user) throws PreexistingEntityException, RollbackFailureException, Exception {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
em.persist(user);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
if (findUser(user.getIdentifier()) != null) {
throw new PreexistingEntityException("User " + user + " already exists.", ex);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
GenerationStrategy.Identity 错误(基本上是说 ID 字段为空(:
ex = (javax.validation.ConstraintViolationException) javax.validation.ConstraintViolationException: Bean Validation constraint(s) violated while executing Automatic Bean Validation on callback event:'prePersist'. Please refer to embedded ConstraintViolations for details.
GenerationStrategy.Sequence 錯誤(表和自動產生相同的例外(:
ex = (org.eclipse.persistence.exceptions.DatabaseException) Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException. Internal Exception: java.sql.SQLSyntaxErrorException: SEQUENCE 'SEQ_GEN_SEQUENCE' does not exist. Call: VALUES(NEXT VALUE FOR SEQ_GEN_SEQUENCE) Query: ValueReadQuery(sql="VALUES(NEXT VALUE FOR SEQ_GEN_SEQUENCE)")
不要对使用GenerationType.IDENTITY
策略生成的@Id
属性使用@NotNull
约束。问题已@NotNull
,并且在提交之前验证了其他JSR-303
约束。在提交完成之前,自动递增的标识符不可用。
试试这个,不要再关心ID初始化了:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "IDENTIFIER", nullable = false, unique = true)
private Long identifier;
当我在标识符上使用自动增量时,我这样做:
User user = new User();
user.setIdentifier((long) 0);// Assign 0 to ID for MSSQL/MySQL to properly auto_increment the primary key.
user.setUserName("some name");
...
使用此 id 注释:
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@NotNull
@Column(name = "ID")
private Long id;