views:

101

answers:

3

I'm using java persistence to save a list of entities that are associated to another entity. Here's a quick rundown of where I'm having some problems.

@Entity public class Offer implements Serializable {
  @Id private Long offerId;

  @OneToMany
  @Column List<OfferCategory> offerCategories;
}

@Entity public class OfferCategory implements Serializable {

  @Embeddable public static class Id implements Serializable
  {
      @Column(name="offer_id")
      private Long offerId;

      @Column(name="category_id")
      private Long categoryId;

      public Id() {}

      public Id(Long offerId, Long categoryId) {
          this.offerId = offerId;
          this.categoryId = categoryId;
      }

      public boolean equals(Object o) {
          if(o != null && o instanceof Id) {
              Id other = (Id) o;
              return this.offerId.equals(other.offerId) &&
                      this.categoryId.equals(other.categoryId);
          }
          else
              return false;
      }

      public int hashCode() {
          return offerId.hashCode() + categoryId.hashCode();
      }
  }
  @EmbeddedId private Id id = new Id();
}

Essentially, due to an architecture I cannot change, I need to save a list of Categories as being assigned to an Offer.

Right now, I'm getting a list of Categories from the user and then putting them into the offerCategories field of Offer. However, this doesn't work for new Offers, because there's no way for me to set the ID of a new item.

I'm new to JPA and Seam, so if someone could give me a nudge in the right direction it would be greatly appreciated.

A: 

I have not tried using a composite ID before, but one thing to note is that @Column is only used to change the properties of the database column the field is using. It doesn't stipulate a relation, so you still need something like this:

@OneToMany    
List<OfferCategory> offerCategories;
shipmaster
A: 

As I looked into tutorial I found this:

You cannot use an IdentifierGenerator to generate composite keys. Instead the application must assign its own identifiers.

So you have to assign the id by yourself. Maybe you can make a DB sequence and fetch its values with native query?
And one remark - if you want to use List mapping (order of Categories in Offer is defined by database), you need an index column to contain the index in list. If the order of categories is not important, Set would be more convenient.

Tadeusz Kopec
But if they're all children of Offer, and I assign them a category, shouldn't it be able to fill in the id at the same time a new id is assigned to Offer?
JBristow
A: 

Well, my solution for now is that I persist each one (creating keys for new entries), then stuff them into a list, then stuff them into their container object, then persist that object.

JBristow