I have a database in which all of the tables have been generated by Java JPA/Hibernate code. I need to update several tables in my database in a fashion similar to this,
UPDATE Department SET id=100000 WHERE id=0;
Unfortunately this results in the error
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (departmentuserlink, CONSTRAINT FK96AF44EAB09C41C5 FOREIGN KEY (department_id) REFERENCES department (id))
Here are the Java entities:
@Entity
@Table(name="Department")
public class Department extends AbstractEntity implements IAbstractEntity {
@OneToMany(cascade=CascadeType.ALL, mappedBy="department", fetch=FetchType.EAGER)
private Set<DepartmentJobLink> departmentJobs = new HashSet<DepartmentJobLink>(0);
//Setters & getters and all that
}
@Entity
@Table(name="edrDepartmentJobLink", uniqueConstraints={@UniqueConstraint(columnNames={"department_id", "job_id"})})
public class DepartmentJobLink extends AbstractEntity implements IAbstractEntity {
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="department_id", nullable=false)
private Department department;
//Setters & getters and all that
}
They both have ID’s in the superclass. So far it looks like everything else about them works great, just running into trouble with updating the primary key of Department. I would appreciate any advice. Thanks.
Well, what foreign keys does the table being updated have? Sounds like you cannot change the value of
department.idbecause some other table has a foreign key constraint on it’sdepartment_idcolumn pointing todepartment.id.This is actually “A Good Thing” since it means your data is reliable.
You need to change your update statement so that you are also updating the
department_idcolumn of the affected table along withdepartment.id(as well as any other affected tables), or optionally you couldALTERthe foreign key constraint so that changes are cascaded. The syntax to do this will vary with your Database implementation.This actually doesn’t have anything to do with JPA or Hibernate – it’s purely a result of foreign-key constraints declared in your database (which may have come from a Hibernate mapping and auto-generating the database schema from a Hibernate schema generator tool, but that is irrelevant now).