Custom wrapper for id key
I want to wrap id in custom class. Like this
@Entity
@Table(name = "USERS")
public class User {
@EmbeddedId
UserId id;
}
@Embeddable
public class UserId implements Serializable开发者_如何学C {
private Long value;
}
The issue in auto generation value
for UserId
. What I should do to make @GeneratedValue
on value
be workable?
BTW, It would be great if id
would be initialized automatically itself.
As far as I know Hibernate only generates values for a field marked as the @Id. I found this post and Hardy's answer supports this.
We have tried to do similar and managed it via a pre-insert listener. It was fairly complex and non-ideal though. Also you might find different behaviour on different database palatforms. Using Oracle sequences would mean that you need to assign the value pre-insert (Hibernate does a select to get the value and then an insert) but with MySQL the auto incrementing field would assign the value and hibernate does an insert to generate the auto generated value and then select to find out what the value was.
精彩评论