开发者

How to tell JPA to use a field of a simple class as the persistence value?

Consider this class:

@Entity
class Bar {
    @Id
    private long id;
    private FooId fooId;
    /* ... */
}

Where Foo is basically just:

class FooId {
    private String id;
    /* ... */
}

I (of course) get the error that "Basic attributes can only be of the following types: ...".

Is there a way to tell JPA (or EclipseLink) to 开发者_StackOverflow中文版treat my fooId field in Bar as a String?

The reason I'm using some "wrapper" type instead of a plain String is that I want to enforce a bit of type-safety in my APIs.

E. g. getAllFooWithBaz(FooId fooId, BazId bazId) instead of getAllFooWithBaz(String fooId, String bazId).

Or is there a better way to achieve that?


This is a common requirement. Try this:

@Entity
class Bar {
    @EmbeddedId
    private FooId fooId;
    /* ... */
}

and:

@Embeddable
class FooId {
    private String id;
    /* ... */
}

or (underlying database schema and FooId remain the same):

@Entity
@IdClass(FooId.class)
class Bar {
    @Id
    private String fooId;
    /* ... */
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜