是否可以不使用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.
因此,休眠后,休眠状态将进行附加查询以填充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.
您应该有一个休眠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屋!