Hi
I am using Hibernate 3.2.6 and i have defined OneToMany mapping from Person to Car as follows.
Code:
@Entity
@Table (name = "kperson")
public class Person
{
@Id
@Column(name = "id")
@GeneratedValue (strategy = GenerationType.IDENTITY)
Integer myId;
@CollectionOfElements(fetch = FetchType.EAGER)
@OneToMany(cascade = { CascadeType.ALL})
@JoinTable(name="kperson_cars",
joinColumns={@JoinColumn(name="person_id")},
inverseJoinColumns={@JoinColumn(name="car_id")})
@Cascade(value = {org.hibernate.annotations.CascadeType.SAVE_UPDATE,
org.hibernate.annotations.CascadeType.MERGE})
@Fetch(FetchMode.JOIN)
Set<Car> myCars;
}
Code:
@Entity
@Table (name = "kcar")
public class Car
{
@Id
@Column(name = "id")
@GeneratedValue (strategy = GenerationType.IDENTITY)
Integer myId;
@Column(name = "name")
String myName;
public Car()
{
}
public Car(String name)
{
myName = name;
}
public boolean equals(Object o)
{
if (!(o instanceof Car))
return false;
Car other = (Car) o;
return myName.equals(other.myName);
}
public int hashCode()
{
return myName.hashCode();
}
}
Now on executing the below code, i am getting 2 cars with same name (Test#2) into kcar table. Can any one tell me how to fix this problem?
Code:
public static void main(String...strings)
{
ArrayList<Car> carTempList = new ArrayList<Car>();
HibernateUtil.init("....");
Person p = HibernateDAO.findUniqueByCriteria(Person.class,
Restrictions.idEq(1));
for (Car c : p.myCars) {
carTempList.add(c);
}
Car aCar = new Car();
aCar.myName = "TEST#2";
p.myCars.add(aCar);
carTempList.add(aCar);
Transaction t = HibernateDAO.getSession().beginTransaction();
HibernateDAO.merge(p);
t.commit();
// get newly inserted car from internally maintained list.
Car sameCar = carTempList.get(carTempList.size() - 1);
p.myCars.remove(aCar);
p.myCars.add(sameCar);
t = HibernateDAO.getSession().beginTransaction();
HibernateDAO.merge(p);
t.commit();
}
Thanks