Hi All,
I am having one to many relationship as follow :
A person can have multiple vehicles;
so in person class I have following code
Code:
@Entity
public class Student {
@Id
@GeneratedValue
private int id;
private String fname;
private String lname;
@OneToMany(fetch=FetchType.LAZY,cascade=CascadeType.ALL)
@JoinTable(inverseJoinColumns=@JoinColumn(name="vehicle_id"))
private Collection<Vehicle> listOfVehicle = new ArrayList<Vehicle>();
public Collection<Vehicle> getListOfVehicle() {
return listOfVehicle;
}
public void setListOfVehicle(Collection<Vehicle> listOfVehicle) {
this.listOfVehicle = listOfVehicle;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
}
Vehicle.java
Code:
@Entity
public class Vehicle {
@Id
@GeneratedValue
private int id;
private String vehicleName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getVehicleName() {
return vehicleName;
}
public void setVehicleName(String vehicleName) {
this.vehicleName = vehicleName;
}
}
and in some other class with main method I am having following code
Code:
public static void createPersontAndAttachExistingVehicle() {
HibernateTier.openHibernaeSession();
Vehicle vehicle = (Vehicle) HibernateTier.session.get(Vehicle.class, 2);
System.out.println(vehicle.getVehicleName());
Person person = new Person ();
person .setFname("NewPersonAndAttachExistingVehicle");
person .getListOfVehicle().add(vehicle);
HibernateTier.session.persist(std);
HibernateTier.closeHibernateSession();
}
What I am trying to do is , I am trying to attach a existing vehicle to new person . But it is throwing an exception like unique constraint is violated. I am not getting where I am making mistake ....
Please help.