gpt4 book ai didi

java - JPA - 主键前缀

转载 作者:太空宇宙 更新时间:2023-11-04 06:19:03 25 4
gpt4 key购买 nike

我们有一个表,其中 ID 由触发器生成 -

ID = year+month+sequence

我通过 JPA 映射了表,我也想在我的代码中使用相同的 PK 生成。我尝试了以下选项:

    @Id
@SequenceGenerator(name = "assetSeq", sequenceName = "ASSET_SEQ")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "assetSeq")
@Transient
private long id;

还尝试更改 setter

   public void setId(long id) {

String finalId=getIdPrefix()+id;
this.id = Long.parseLong(finalId);

}

private String getIdPrefix() {
DateFormat df = new SimpleDateFormat("YYYYMM");
Date today = Calendar.getInstance().getTime();
return df.format(today);
}

但它们都不起作用。我只想在数据库中插入新记录,不想稍后使用该 id。我将 Hibernate 用于 JPA

最佳答案

如果您实现自定义 Hibernate 生成器,则可以执行此操作。 This blog有与您需要的几乎相同的示例。我将在此处发布根据您的需求调整的博客代码(如果您复制粘贴它可能不起作用,但它会接近)

public class CustomIdGenerator implements IdentifierGenerator {

public Serializable generate(SessionImplementor session, Object object)
throws HibernateException {

String prefix = getIdPrefix();
Connection connection = session.connection();
try {

PreparedStatement ps = connection
.prepareStatement("SELECT nextval ('ASSET_SEQ') as nextval"); // could be different, depending on database vendor

ResultSet rs = ps.executeQuery();
if (rs.next()) {
int id = rs.getInt("nextval");
String code = prefix + id;
return code;
}

} catch (SQLException e) {
throw new HibernateException(
"Unable to generate ID");
} finally {
if (ps != null) {
try {
ps.close();
} catch (Throwable e) {
// log error, or rethrow exception
}
}
}
return null;
}

private String getIdPrefix() {
DateFormat df = new SimpleDateFormat("YYYYMM");
Date today = Calendar.getInstance().getTime();
return df.format(today);
}

}

@Id
@GenericGenerator(name="seq_id", strategy="my.package.CustomIdGenerator")
@GeneratedValue(generator="seq_id")
// don't put that @Transient here
private long id;

希望这有帮助。

关于java - JPA - 主键前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27690709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com