java - TransientObjectException even if I set cascade=CascadeType.ALL -
i've 2 classes:
employee.java
@entity @table public class employee { @id @generatedvalue private long id; private string name; @manytoone private department department; public employee() {} public employee(string name, department department) { this.name = name; this.department = department; } public employee(string name) { this.name = name; } public long getid() { return id; } public void setid(long id) { this.id = id; } public string getname() { return name; } public void setname(string name) { this.name = name; } public department getdepartment() { return department; } public void setdepartment(department department) { this.department = department; } @override public string tostring() { return "employee [id=" + id + ", name=" + name + ", department=" + department.getname() + "]"; } }
department.java
@entity @table public class department { @id @generatedvalue private long id; private string name; @onetomany(mappedby="department",cascade=cascadetype.all) private list<employee> employees = new arraylist<employee>(); public department() { super(); } public department(string name) { this.name = name; } public long getid() { return id; } public void setid(long id) { this.id = id; } public string getname() { return name; } public void setname(string name) { this.name = name; } public list<employee> getemployees() { return employees; } public void setemployees(list<employee> employees) { this.employees = employees; } }
then tried save department
, employees
in main method:
session session = hibernateutil.getsessionfactory().opensession(); session.begintransaction(); department department = new department("java"); //session.save(department); //throw org.hibernate.transientobjectexception if comment line session.save(new employee("jakab gipsz",department)); session.save(new employee("captain nemo",department)); session.gettransaction().commit();
it didn't work. throwed error:
org.hibernate.transientobjectexception: object references unsaved transient instance - save transient instance before flushing: com.learn.hibernate.department
but if uncommented line session.save(department);
, worked fine. why? i've set cascade=cascadetype.all
, supposed save department
automatically without throwing errors. did miss anything?
when save employee, department not saved because there no cascade. if want that, need add cascade in employee class.
@manytoone(cascade = cascadetype.save) private department department;
Comments
Post a Comment