开发者

How to store the same entity in mulitple lists in Hibernate using JPA

Im very new to Hibernate so this will probably a easy task for you guys.

As the Topic says I'm trying to reference the same entity in multiple Lists. But when I try to do so I get an exception saying: "Duplicate entry '5' for key 'military_id'". I googled but could not find a solution to my problem.

I have an Entity called MilitaryUnitData like this:

@Entity
public class MilitaryUnitData implements IMovable{
   private long Id;

//snip

   @Id
   @GeneratedValue(strategy=GenerationType.TABLE)
   public long getId() {
      return Id;
   }
   public void setId(long id) {
      Id = id;
   }

       //snip
}

and a class City where I want to store m开发者_Go百科y units in.

@Entity
public class CityData {

private Collection<MilitaryUnitData> military = new ArrayList<MilitaryUnitData>();
private String name;

//snip

@Id
   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

@OneToMany
   @Column(nullable=false)
   public Collection<MilitaryUnitData> getMilitary() {
      return military;
   }

   public void setMilitary(Collection<MilitaryUnitData> military) {
      this.military = military;
   }

//snip
}

The problem occurs when I want to put a Unit into 2 cities at the same time. How do I have to change the mapping to achive this?

Thx in advance.


I'm trying to reference the same entity in multiple Lists After looking at your code, I think you mean, that the same MilitaryUnitData is used in several CityData?

IF this is correct, than the realtion ship is a M:N relation ship, and you need to use a @ManyToMany instead of an @OneToMany.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜