4.5. Working with Simple Collections

The collections we've been looking at so far have all contained associations to other objects, which is appropriate for a chapter titled "Collections and Associations," but isn't the only kind you can use with Hibernate. You can also define mappings for collections of simple values, like strings, numbers, and nonpersistent value classes.

4.1.1. How do I do that?

Suppose we want to be able to record some number of comments about each track in the database. We want a new property called comments to contain the String values of each associated comment. The new mapping in Tracks.hbm.xml looks a lot like what we did for artists, only a bit simpler:

	<set name="comments" table="TRACK_COMMENTS">
	  <key column="TRACK_ID"/>
	  <element column="COMMENT" type="string"/>
	</set>

Since we're able to store an arbitrary number of comments for each Track, we're going to need a new table to put them in. Each comment will be linked to the proper Track through the track's id property.

Rebuilding the databases with ant schema shows how this gets built in the database:

	[schemaexport] create table TRACK_COMMENTS (
	[schemaexport]    TRACK_ID INTEGER not null,
	[schemaexport]    COMMENT VARCHAR(255) 
	[schemaexport] )
	[schemaexport] alter table TRACK_COMMENTS add constraint FK105B26884C5F92B
	foreign key (TRACK_ID) references TRACK

Data modeling junkies will recognize this as a "one-to-many" relationship.

After updating the Track class via ant codegen, we need to add another Set at the ...

Get Hibernate: A Developer's Notebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.