简体   繁体   English

java如何设置自增属性

[英]java how to set an auto increment attribute

In my entity I have this code:在我的实体中,我有以下代码:

@Entity
@Table(name = "product")
class Product{   
...
    @GeneratedValue(strategy=GenerationType.AUTO)
    int rank;
}

When I try to save an object of type product, in DB, the rank value remains always 0当我尝试保存产品类型的对象时,在数据库中,排名值始终为 0

Can I set an attribute other than the id auto-increment?我可以设置 id 自动递增以外的属性吗?

The solution proposed by @Alain Cruz, is the way! @Alain Cruz 提出的解决方案就是这样! But it is the half of the answer... You will need:但这是答案的一半......你将需要:

1) To Modify your rank attribute like this: 1) 像这样修改你的rank属性:

@Generated(GenerationTime.INSERT)
@Column(name = "column_name", insertable = false)
Long rank;

2) Create a before insertion trigger that monitors Products entities, checking that if rank comes null , you will change that value for a new value returned by the desired sequence... 2) 创建一个监控Products实体的插入前触发器,检查是否 rank 为null ,您将更改该值以使用所需序列返回的新值...

I have done this approach to generate special codes using SQL Functions stored in my database... You can find more info here我已经完成了这种使用存储在我的数据库中的 SQL 函数生成特殊代码的方法......您可以在此处找到更多信息

There are different ways to auto generate a value, but they must always be done on the @Id field.有多种方法可以自动生成值,但它们必须始终在@Id字段上完成。 If it is not declared, then you won't be able to auto increment your value.如果未声明,则您将无法自动增加您的价值。

There are different types of strategies to increment your Id.有不同类型的策略可以增加您的 ID。 In this blog , you can learn more about them.在此博客中,您可以了解更多关于它们的信息。 For your example, IDENTITY should do the trick.对于您的示例, IDENTITY 应该可以解决问题。

@Entity
@Table(name = "product")
class Product{   

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    int rank;
}

Update更新

After doing some research, it seems that Hibernate now allows to auto increment other non-id fields, but it uses another annotation for the purpose.经过一些研究,Hibernate 现在似乎允许自动增加其他非 id 字段,但它为此使用了另一个注释。 I haven't tried it, but maybe it could work.我还没有尝试过,但也许它可以工作。 This in case your rank is not your id.以防您的等级不是您的 ID。

@Generated(GenerationTime.INSERT)
@Column(name = "column_name", insertable = false)
int rank;
@Entity
@Table(name = "product")
class Product{   
...
    @GeneratedValue(strategy=GenerationType.IDENTITY )
    int rank;
}

The following should work and if it does not, then try what comes after:以下应该有效,如果无效,请尝试之后的操作:

@Entity
@Table(name = "product")
class Product{   
...
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int rank;
}

public int getId() {
    return id;
}



public void setId(int id) {
    this.id = id;
}

If that does not work, then go to your database and set rank variable to be auto incremented.如果这不起作用,请转到您的数据库并将排名变量设置为自动递增。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM