I’m facing a problem while deleting a record that is referenced by another table.
This is a code example (simplest scenario):
@Entity
@Table(name = "user")
public class User
{
@Id
@GeneratedValue(generator="user_id_seq", strategy = GenerationType.SEQUENCE)
@SequenceGenerator(name="user_id_seq", sequenceName="user_id_seq")
@Column(name = "id", nullable = false)
private int id;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
private Set<UserLog> userLogSet;
// Other attributes
// Getters/setters
}
@Entity
@Table(name = "user_log")
public class UserLog
{
@Id
@GeneratedValue(generator="user_log_id_seq", strategy = GenerationType.SEQUENCE)
@SequenceGenerator(name="user_log_id_seq", sequenceName="user_log_id_seq")
@Column(name = "id", nullable = false)
private int id;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "user_id", nullable = false)
private User user;
// Other attributes
// Getters/setters
}
Whenever I try to delete a record from the “user” table, I get the following error from postgreSQL:
ERROR: update or delete on table “user” violates foreign key
constraint “fk228a019fd2495d20” on table “user_log”
Detail: Key
(id)=(5) is still referenced from table “user_log”.
What am I doing wrong?
Thank you!
Update: I tried coding a small example, it can be found here. After launching the application with Tomcat the database schema is automatically created (check the connection details in /src/main/webapp/WEB-INF/jdbc.properties). When you visit http://localhost:8080 some data is inserted in the database. If I try to delete any teacher who is referenced in the student table (using phpPgAdmin), I get an error similar to the one above.
Your mapping seems to be wrong.
User can have many UserLogs I guess.
Also
@OneToManyshould be on a collection e.g.java.util.Set.The cascade you have put is in UserLog which will take place if you act on instance of UserLog and not User.
As far as I understand change mapping as follows.
I guess you want to delete User and all its UserLog simply deleting User and leaving UserLogs doesn’t make sense.
Hope this helps.
Update: