问题
Suppose I have a Players
table:
ID | name | email | age | ...
1 | 'bob' | null | 23 | ...
There is a lot of columns (say, 50) and each (apart from ID
) might be null. Please disregard the table design, it's has to stay this way for now :-(
I'd want to map this table to an entity (i.e. i'd like it to work for both saving and reading):
public class Player implements Serializable {
private Map<String, String> attributes;
// more code, ctor, setters, getters etc...
}
where each column in the table is read as an entry to the map. So in the given example the map would have keys ID
, name
, email
etc. with appropriate values.
I can live with a separate id
member if that's required by Hibernate, but I want to avoid having 50 members in one class.
Is this possible in Hibernate 4?
回答1:
I'm not sure if maintaining a Map
is possible and if it is, how does it impact readability.
But you can use the @Embeddable
and @AttributeOverride
anotations instead.
In order to avoid having 50 members in one class, you can group the members by some common property and place each of the groups in a separate class. Then, you will have to annotate each of the classes with @Embeddable
which will make their instance Embeddable objects (or components). These are objects whose properties are mapped to the same table as the owning entity's table. For example, let's say you've decided to group the name
, age
and email
properties in a single class, called PersonalData
Optionally, you can name the properties whatever you like, but then you will have to use the @Column
annotation to tell Hibernate about which exact database table-column are you talking about.
@Embeddable
public class PersonalData implements Serializable {
private String fullname;
private String email;
private String age;
//accessors
}
You can create as much as @Embeddable
-annotatated classes you need. It's not a good idea to have a single @Embeddable
class with 50 members, so you can spread the members across several classes.
After done, we go back to the @Entity
-annotated class. Its members will be instances of the @Embeddable
classes annotated with the Embeddable
anotation. The @AttributeOverrides
annotation will be helpful to match each of the embedded component's members to a specific database table-column. For example:
@Entity
public class Person implements Serializable {
@Embedded (
@AttributeOverrides(name = "fullname", column = @Column(name = "name"))
@AttributeOverrides(name = "email", column = @Column(name = "email"))
@AttributeOverrides(name = "age", column = @Column(name = "age"))
)
private PersonalData personalData;
//other @Embedded-annotated members.
}
来源:https://stackoverflow.com/questions/21904041/maps-entries-to-separate-columns-in-hibernate