简体   繁体   English

@GeneratedValue 注释

[英]@GeneratedValue annotation

I have an entity which has a non-key column which I've set as auto-generated in my DB.我有一个实体,它有一个非键列,我在我的数据库中设置为自动生成。

I cannot use @GeneratedValue because it works only for key fields as far as I understand.我不能使用@GeneratedValue ,因为据我所知,它仅适用于关键字段。

Given this case, how do I indicate that the non-key column is auto-generated?鉴于这种情况,我如何指示非键列是自动生成的?

If you are not interested in having your JPA provider generate the key for you on object creation, but only want to make sure it stays updated when the database creates it, and are using Hibernate: you can use the @org.hibernate.annotations.Generated annotation: If you are not interested in having your JPA provider generate the key for you on object creation, but only want to make sure it stays updated when the database creates it, and are using Hibernate: you can use the @org.hibernate.annotations.Generated注释:

The annotated property is generated by the database.

According to this answer to a similar question It doesn't look like there is a simple way to have your JPA generate the value for you.根据this answer to a similar question看起来没有一种简单的方法可以让您的 JPA 为您生成值。

I had exactly the same problem and resolved it using the @PrePersist annotation.我遇到了完全相同的问题,并使用@PrePersist注释解决了它。

Use it on a method in which you manipulate your field.在您操作字段的方法上使用它。

Warning: this function is called each time you persist your entity, so don't forget to test if the value has been initialized or not.警告:每次持久化实体时都会调用此 function,因此不要忘记测试该值是否已初始化。

Hope that helped.希望有帮助。 I'm interested of other ways of doing that !我对其他方法感兴趣!

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

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