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;
/* ... */
}
精彩评论