An author of a project isn't changed as long as the column/project exists (updatable = false), it looks like this:
Code:
class Project {
...
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "author", updatable = false)
public Student getAuthor() { //this value can only be inserted on creation
return author;
}
...
}
What I tried looked like this, but this doesn't work:
Code:
class StudentDAO {
...
public Student delete(Serializable id) {
if (id instanceof Student) {
id = ((Student) id).getId();
}
Student student = null;
Session session = null;
try {
session = HibernateUtil.currentSession();
session.beginTransaction();
student = (Student) session.get(clazz, id);
for (Project project : student.getProjects()) {
project.setAuthor(null); //need to null out the reference here to delete the student without deleting the project
student.getProjects().remove(project);
}
session.delete(student);
session.getTransaction().commit();
} catch (HibernateException e) {
session.getTransaction().rollback();
throw e;
}
return student;
}
...
}
So my current workaround is this, but is there a better/easier way:
Code:
class StudentDAO {
...
public Student delete(Serializable id) {
if (id instanceof Student) {
id = ((Student) id).getId();
}
Student student = null;
Session session = null;
try {
session = HibernateUtil.currentSession();
session.beginTransaction();
student = (Student) session.get(clazz, id);
for (Project project : student.getProjects()) {
final Integer pid = projekt.getId();
session.doWork(new Work() {
@Override
public void execute(Connection connection)
throws SQLException {
connection.createStatement().execute( //the current workaround I don't really like
"update project set "
+ "author=null "
+ "where id =" + pid);
}
});
}
student.getProjects().clear();
session.delete(student);
session.getTransaction().commit();
} catch (HibernateException e) {
session.getTransaction().rollback();
throw e;
}
return student;
}
...
}
Is it somehow possible use pure Hibernate code to do the same?