1 Reply Latest reply on Jan 25, 2005 5:41 PM by Michael Ralston

    @Inject into an Entity Bean ... or Map Collection

    Michael Ralston Newbie

      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();
       }
      }
      

      ExampleBean1 and ExampleBean2 are two ways I've thought of doing this so far but neither of them actually work.

      Any ideas on how either of them could work or any other way to do the same thing?