Tutorial :Mapping a ManyToMany relationship with hibernate annotations?



Question:

Table Layout:

  TABLE ORDER:  id   localizedInfoId    Table OrderLocalizedInfo:  id  localizedInfoId  name  

With the following entities:

      public class Order {      @Id      @GeneratedValue(strategy = GenerationType.AUTO)      @Column(name="id")     private Long id;        @ManyToMany(          targetEntity=OrderLocalizedInfo.class,          cascade={CascadeType.PERSIST, CascadeType.MERGE})      @JoinTable(          name="OrderLocalizedInfo",          joinColumns=@JoinColumn(name="localizedInfoId"),          inverseJoinColumns=@JoinColumn(name="localizedInfoId"))     private List localizedInfos;  }    public class OrderLocalizedInfo {       @Id      @GeneratedValue(strategy = GenerationType.AUTO)      @Column(name="id")     private Long id;        @Column(name="localizedInfoId")     private Long localizedInfoId;        @Column(name="name")     private String name;  }    

I want to map the above situation so that I have a list of OrderLocalizedInfo objects on the order object, using the 'localizedInfoId' field in each table. When I do this I get a mapping exception 'Repeated column mapping for collection Order.localizedInfos column: localizedInfoId.


Solution:1

I don't really understand your physical model but it clearly doesn't represent a many to many association. A many to many association between A and B involves a join table that contains columns for the primary keys of the source and target tables:

  +-------+    +-------+    +-------+  |   A   |    |  A_B  |    |   B   |  +-------+    +-------+    +-------+  | A_ID  |    | AID   |    | B_ID  |  | ...   |    | BID   |    | ...   |  +-------+    +-------+    +-------+  

So currently, there is nothing to map with @ManyToMany. You need to either fix your physical model or clarify what you're trying to achieve (maybe it's not a many to many after all).


Solution:2

As Pascal said, there isn't a ManyToMany relationship present as shown. Your current model suggesting a List of OrderLocalizedInfo objects would be better represented in Hibernate as a OneToMany Collection - http://docs.jboss.org/hibernate/core/3.5/reference/en/html/collections.html


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »