是否可以在没有 ID 的情况下使用自动增量编号? [英] Is it possible to have autoincrement number without it being an ID?
问题描述
我一直在谷歌搜索,发现唯一的方法就是使用
I keep googling and find that the only way is to use
@Id
@GeneratedValue(strategy = GenerationType.Identity)
但是我已经有了一个主键,我只需要另一个自动递增的字段.手动计算代码真的很难.
But I already have a primary key, I just need another field that auto increments. It's really hard to code it by manual calculation.
推荐答案
我看到以下选项:
1) 您可以使用 @Generated 注释.
1) You can use @Generated annotation.
您应该按以下方式声明一个表:
You should have a table declared in the following way:
create sequence TST_DATA_SEQ increment by 1 start with 1;
create table TST_DATA (
...
dat_auto integer default nextval('TST_DATA_SEQ'),
...
);
和实体中的适当列:
@Generated(value = GenerationTime.INSERT)
@Column(name = "dat_auto", insertable = false, updatable = false)
private Long auto;
请注意,根据文档:
标记为生成的属性还必须是不可插入和不可更新的.
Properties marked as generated must additionally be non-insertable and non-updateable.
因此,hibernate 将在刷新后进行额外查询以填充 auto
字段.
So, hibernate will make additional query to populate the auto
field after flushing.
Data data = new Data();
// filling fields except data.auto
session.persist(data);
session.flush();
insert into TST_DATA (dat_name, dat_id)
values (?, ?)
Hibernate: /* get generated state com.example.hibernate.Data */
select data_.dat_auto as dat_auto_0_
from TST_DATA data_
where data_.dat_id=?
2) 您可以使用 @GeneratorType 注释.
2) You can use @GeneratorType annotation.
您应该有一个 hibernate ValueGenerator
的实现.您可以在下面看到的简单示例.
You should have an implementation of hibernate ValueGenerator
. The simple example you can see below.
import java.math.BigInteger;
import org.hibernate.Session;
import org.hibernate.tuple.ValueGenerator;
public class MyGenerator implements ValueGenerator<Long>
{
public Long generateValue(Session session, Object owner)
{
return (
(BigInteger) session
.createNativeQuery("select nextval('TST_DATA_SEQ')")
.getSingleResult()
).longValue();
}
}
然后你可以像这样使用它:
And then you can use it like this:
@GeneratorType(type = MyGenerator.class, when = GenerationTime.INSERT)
@Column(name = "dat_auto")
private Long auto;
在这种情况下,您不应像 n1 中要求的那样为列声明提供默认值.并且相应的实体字段不应具有 @Column(... insertable = false, updatable = false)
.每次持久化这个实体时,hibernate 都会生成查询:
In this case you should not provide the default value for the column declaration as was required in n1. and the appropriate entity field should not have @Column(... insertable = false, updatable = false)
. Each time when this entity will be persisted, hibernate generates query:
select nextval('TST_DATA_SEQ')
并将此值填充到 auto
字段.
and populate this value to the auto
field.
这篇关于是否可以在没有 ID 的情况下使用自动增量编号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!