简体   繁体   中英

Why is it the best way to initialize the collection value property of a newly instantiated (non-persistent) instance?

See https://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/collections.html#collections-persistent

Notice how in Example 7.2, “Collection mapping using @OneToMany and @JoinColumn” the instance variable parts was initialized with an instance of HashSet. This is the best way to initialize collection valued properties of newly instantiated (non-persistent) instances.

I've tried debugging in several ways, but I didn't get a clear answer. What is the reason?

Imho it has done just to prevent possible NullPointerException s within industrial code. Such an initialization guaratees collection existence coz you can't know how and by whom your entities will be used in the future.

and as an affirmation is the next to your quotation sentence:

When you make the instance persistent, by calling persist(), Hibernate will actually replace the HashSet with an instance of Hibernate's own implementation of Set

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM