如何同时持久化实体与其Map集合?JPA代码示例验证
Absolutely yes—when you call testRepository.save(test) after adding an entry to the map, both the main Test entity and the new Map entry will be persisted to the database. Let me break down why this works with your code example:
How @ElementCollection Enables This
The @ElementCollection annotation is specifically designed in JPA to map collections of non-entity types (like your Map<Long, Long> of wrapper classes). It creates a dependent relationship between your main Test entity and the associated table (test1_id in your case). JPA automatically manages the persistence, updates, and deletion of this collection alongside the main entity's lifecycle.
Walkthrough of Your Code's Behavior
Looking at your entity mapping:
public class Test { private @Id @GeneratedValue(strategy = AUTO) Long id; private String name; @ElementCollection(targetClass = Long.class) @CollectionTable(name = "test1_id") @MapKeyColumn(name = "test_id") @Column(name = "test") private Map<Long, Long> map = new HashMap<>(); }
When you run:
test.getMap().put(1L, 2L); testRepository.save(test);
- If
testis a new (unpersisted) entity: JPA first inserts a record into theTesttable, generates itsid, then inserts a corresponding record into thetest1_idtable. This record will have:- A foreign key linking to the new
Testentity'sid test_idset to1L(the Map's key)testset to2L(the Map's value)
- A foreign key linking to the new
- If
testis an existing (persisted) entity: Callingsave()triggers a merge operation. JPA detects the change to themapcollection and automatically inserts the new entry into thetest1_idtable.
Key Additional Notes
- Cascade Behavior: By default,
@ElementCollectionincludesCascadeType.PERSISTandCascadeType.MERGE—this is why changes to the collection are automatically synced when you save the main entity. - Lazy Loading: The collection uses
FetchType.LAZYby default. If you need to access themapoutside of a persistence context, either switch toFetchType.EAGERor ensure you load the collection within an active transaction. - Updates/Deletions: This synchronization works for more than just new entries—if you modify or remove entries from the
map, those changes will also be reflected in thetest1_idtable when you save the entity or the transaction commits.
内容的提问来源于stack exchange,提问作者ganymede

