一、结构
二、代码
1.
1 package org.jpwh.model.collections.mapofstrings; 2 3 import org.jpwh.model.Constants; 4 5 import javax.persistence.CollectionTable; 6 import javax.persistence.Column; 7 import javax.persistence.ElementCollection; 8 import javax.persistence.Entity; 9 import javax.persistence.GeneratedValue; 10 import javax.persistence.Id; 11 import javax.persistence.MapKeyColumn; 12 import java.util.HashMap; 13 import java.util.Map; 14 15 @Entity 16 public class Item { 17 18 @Id 19 @GeneratedValue(generator = Constants.ID_GENERATOR) 20 protected Long id; 21 22 @ElementCollection 23 @CollectionTable(name = "IMAGE") 24 @MapKeyColumn(name = "FILENAME") 25 @Column(name = "IMAGENAME") 26 protected Map<String, String> images = new HashMap<String, String>(); 27 28 public Long getId() { 29 return id; 30 } 31 32 public Map<String, String> getImages() { 33 return images; 34 } 35 36 public void setImages(Map<String, String> images) { 37 this.images = images; 38 } 39 40 // ... 41 }
2.
1 package org.jpwh.test.collections; 2 3 import org.jpwh.env.JPATest; 4 import org.jpwh.model.collections.mapofstrings.Item; 5 import org.testng.annotations.BeforeClass; 6 import org.testng.annotations.Test; 7 8 import javax.persistence.EntityManager; 9 import javax.transaction.UserTransaction; 10 11 import static org.testng.Assert.assertEquals; 12 13 public class MapOfStrings extends JPATest { 14 15 @Override 16 public void configurePersistenceUnit() throws Exception { 17 configurePersistenceUnit("MapOfStringsPU"); 18 } 19 20 @Test 21 public void storeLoadCollection() throws Exception { 22 UserTransaction tx = TM.getUserTransaction(); 23 try { 24 tx.begin(); 25 EntityManager em = JPA.createEntityManager(); 26 Item someItem = new Item(); 27 28 someItem.getImages().put("foo.jpg", "Foo"); 29 someItem.getImages().put("bar.jpg", "Bar"); 30 someItem.getImages().put("baz.jpg", "WRONG!"); 31 someItem.getImages().put("baz.jpg", "Baz"); 32 33 em.persist(someItem); 34 tx.commit(); 35 em.close(); 36 Long ITEM_ID = someItem.getId(); 37 38 tx.begin(); 39 em = JPA.createEntityManager(); 40 Item item = em.find(Item.class, ITEM_ID); 41 assertEquals(item.getImages().size(), 3); 42 assertEquals(item.getImages().get("foo.jpg"), "Foo"); 43 assertEquals(item.getImages().get("bar.jpg"), "Bar"); 44 assertEquals(item.getImages().get("baz.jpg"), "Baz"); 45 tx.commit(); 46 em.close(); 47 } finally { 48 TM.rollback(); 49 } 50 } 51 52 }
3.
1 <persistence-unit name="MapOfStringsPU"> 2 <jta-data-source>myDS</jta-data-source> 3 <class>org.jpwh.model</class> 4 <class>org.jpwh.model.collections.mapofstrings.Item</class> 5 <exclude-unlisted-classes>true</exclude-unlisted-classes> 6 </persistence-unit>