开发者

How to generate GUID on demand in hibernate?

I want to generate a GUID id, if user didn't give a name for COMPONENT,

@Entity class Component {

    @Id @Column(length = 32)
    String name; 

}

I can't use generator here, so I can explicit specify the name.

Though I can add another id field, and make name as @NaturalId:

@Entity class Component {

    @Id
    Long id;

    @Column(length = 32)
    String name; 

}

But the question still: How can I generate a GUID for na开发者_开发问答me?

I can write a simple GUID generator myself, but I want to do it Hibernate way.


Try taking a look at the EmptyInterceptor, I think you can catch the onSave event, update your "name" if it is not set.

Just use the UUID class to generate what you need I think it will cover it.

GUID in the case of Hibernate will utilize the database to generate a GUID in the case of mySql and MSSS (I think)

You can scope the interceptor application wide or only for a particular session.

http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/events.html#objectstate-interceptors

Hope that works for you.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜