开发者

@GeneratedValue annotation

I have an entity whi开发者_StackOverflow中文版ch 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.

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:

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.


I had exactly the same problem and resolved it using the @PrePersist annotation.

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.

Hope that helped. I'm interested of other ways of doing that !

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜