当前位置: 首页 > 面试题库 >

JPA:覆盖自动生成的ID

苍兴怀
2023-03-14
问题内容

我在Employee类中有以下定义

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "employee_id")
private Integer employeeId;

现在,我想使用现有员工ID导入现有员工。即使在保存之前设置了员工ID,也会忽略分配的ID,并存储自动递增的ID。我们如何覆盖呢?


问题答案:

我编写了自己的生成器来解决此问题。

public class UseExistingIdOtherwiseGenerateUsingIdentity extends IdentityGenerator {

    @Override
    public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
        Serializable id = session.getEntityPersister(null, object).getClassMetadata().getIdentifier(object, session);
        return id != null ? id : super.generate(session, object);
    }
}

并像这样使用它:(替换包名)

@Id
@GenericGenerator(name = "UseExistingIdOtherwiseGenerateUsingIdentity", strategy = "{package}.UseExistingIdOtherwiseGenerateUsingIdentity")
@GeneratedValue(generator = "UseExistingIdOtherwiseGenerateUsingIdentity")
@Column(unique = true, nullable = false)
protected Integer id;


 类似资料:
  • 我正在编写FastAPI程序,它只是一堆用于查询数据的endpoint。他们可以使用许多不同的查询参数,这些参数是从配置文件中自动生成的,例如endpoint可能看起来像

  • 我使用eclipse生成Object的hashCode和equals方法的覆盖,并生成了一些关于hashCode覆盖的问题。下面的hashCode()是否正确? 问题: -为什么eclipse会生成两行代码?我认为将两个结果相加是合适的。知道为什么它们是分开的任务吗? -最终的int素数可以是任何素数吗? -整数结果是否应始终为 1?

  • 问题内容: 我的主键实体如下所示 当我跑步时,出现错误 无法获取或更新下一个值;嵌套的异常是org.hibernate.exception.SQLGrammerException:无法获取或更新下一个值 但是当我改变为 没有错误抛出。我想在 oracle db 上为每个表生成唯一的主键。 问题答案: 当将新创建的实体插入数据库时,告诉JPA提供者使用表从中获取ID。 当使用Hibernate作为提

  • 我正在使用supportlib v4来实现主细节流。 方法在单击后调用:

  • 我希望它改用id: 我正在对ObjectMapper进行子类化,所以也许有一些方法可以挂钩

  • 我们没有本地存储,每次我们在POD部署时生成idp元数据。 然而,SP还需要处理idp元数据x509证书。有办法处理这种情况吗?