Hibernate如何将部分列映射到内部子Pojo且不新建表?
Absolutely, your proposed approach is exactly the right way to achieve this with Hibernate! The @Embedded and @Embeddable annotations were built specifically for this scenario—grouping related fields into a dedicated class while keeping all data in the same underlying database table (no new USER_STATISTICS table required).
Why this works perfectly for your case:
@Embeddablemarks a class whose fields can be "embedded" directly into another entity's table. It’s a way to encapsulate related data without creating a separate database table.@Embeddedin the parentUserentity tells Hibernate to map the fields ofUserStatisticsdirectly into theUSERtable. The columns forlastVisited,lastPlayed, andlastPayedwill stay in theUSERtable—they’re just grouped into thestatisticsobject in your Java code for better domain modeling.
Optional: Customize column names (if needed)
If you want to clarify the embedded fields in your database (e.g., add a prefix like stats_), you can use @AttributeOverride to adjust column mappings without changing the embedded class:
@Entity @Table(name = "USER") class User { @Id private long id; private String name; private int age; @Embedded @AttributeOverrides({ @AttributeOverride(name = "lastVisited", column = @Column(name = "STATS_LAST_VISITED")), @AttributeOverride(name = "lastPlayed", column = @Column(name = "STATS_LAST_PLAYED")), @AttributeOverride(name = "lastPayed", column = @Column(name = "STATS_LAST_PAYED")) }) private UserStatistics statistics; // getters and setters } @Embeddable class UserStatistics { private long lastVisited; private long lastPlayed; private long lastPayed; // getters and setters }
Key distinctions to note:
- This is not the same as
@OneToOne:@OneToOnewould require a separate table and foreign key relationship, which you explicitly want to avoid. - Hibernate handles the mapping transparently: when you load a
Userentity, thestatisticsfield will automatically populate with the corresponding column values from theUSERtable. - Your database schema remains unchanged—no migrations needed to move fields to a new table.
This is a clean, idiomatic way to organize your domain model while keeping your database structure intact, which is exactly what you’re looking for!
内容的提问来源于stack exchange,提问作者Shvalb

