I've been using ejb3 entity beans to provide persistence to some normal java interfaces.
I have a stateless session bean which I use to retrieve an instance of an entity, then I manipulate the Entity in my java code through the interface which it implements. This might not be the best way to implement entity beans but it's working really well for me so far...
The interface which I am providing requires methods to add and remove items from a collection based on a primary key. For example...
@Entity public class ItemBean implements Item { private String key; private String otherAttribute; @Id public String getKey() { return this.key; } public void setKey(String newKey) { this.key=newKey; } ... } @Entity(access = AccessType.FIELD) public class ExampleBean1 implements Example { @Id(generate = GeneratorType.AUTO) private int id; @OneToMany @JoinColumn(name = "item_key") private Map<String,ItemBean> items=new HashMap<String,ItemBean>(); ... public ItemBean getItem(String key) { return this.items.get(key); } public void addItem(ItemBean item) { this.items.put(item.getKey(),item); } public void removeItem(String key) { this.items.remove(key); } ... } @Entity(access = AccessType.FIELD) public class ExampleBean2 implements Example { @Id(generate = GeneratorType.AUTO) private int id; @OneToMany @JoinColumn(name = "item_key") private Set<ItemBean> items=new HashSet<ItemBean>(); @Inject EntityManager manager; ... public ItemBean getItem(String key) { return this.findItem(key); } public void addItem(ItemBean item) { this.items.add(item); } public void removeItem(String key) { this.items.remove(this.find(key)); } ... private ItemBean findItem(String findKey) { return (ItemBean) this.manager.createQuery("from ItemBean i where i.key= :findKey").setParameter("findKey", findKey).getUniqueResult(); } }
By the way...
ExampleBean1 throws an exception in the EntityToHibernateXML thingo.
ExampleBean2 throws a null pointer exception when I try to use the EntityManager object that I injected. It doesn't seem to be injected, it just remains null