0
@ManyToOne
hibernateマッピングでのレコード挿入を防止する方法。その親テーブルにはレコードがありません。私たちは、親テーブルの主キーなしでレコードを挿入しようとしましたが、まだレコードが子テーブルに挿入された@ManyToOne hibernate mapping
Domain class
Department Table(Parent)
@Table(name = "Department")
@Entity
public class Department {
@Id
@GenericGenerator(name = "g1", strategy = "increment")
@GeneratedValue(generator = "g1")
private int deptno;
private String deptname;
private String depthead;
public Department() {
System.out.println("Department:0-param constuctor");
}
public int getDeptno() {
return deptno;
}
public void setDeptno(int deptno) {
this.deptno = deptno;
}
public String getDeptname() {
return deptname;
}
public void setDeptname(String deptname) {
this.deptname = deptname;
}
public String getDepthead() {
return depthead;
}
public void setDepthead(String depthead) {
this.depthead = depthead;
}
@Override
public String toString() {
return "Department [deptno=" + deptno + ", deptname=" + deptname +
", depthead=" + depthead + "]";
}
}
Emplyee table(child)
@Table(name = "EmpDetails")
@Entity
public class EmpDetails {
@Id
private int eno;
private String ename;
private double salary;
@ManyToOne(targetEntity = Department.class,
cascade = CascadeType.ALL,
fetch = FetchType.LAZY)
@JoinColumn(name = "deptno", referencedColumnName = "deptno")
private Department dept;
public EmpDetails() {
System.out.println("EmpDetails:0-param constructor");
}
public int getEno() {
return eno;
}
public void setEno(int eno) {
this.eno = eno;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public Department getDept() {
return dept;
}
public void setDept(Department dept) {
this.dept = dept;
}
@Override
public String toString() {
return "EmpDetails [eno=" + eno + ", ename=" + ename + ", salary=" +
salary + "]";
}
}
DAO
@Override
public void addEmployeesWithDept() {
// get Session
Session ses = HibernateUtil.getSession();
// create Department (parent)
//Department dept=new Department();
//dept.setDeptname("Accounts");
//dept.setDepthead("Jhon");
//create Employees(childs)
EmpDetails emp1 = new EmpDetails();
emp1.setEno(107);
emp1.setEname("raja");
emp1.setSalary(9000);
EmpDetails emp2 = new EmpDetails();
emp2.setEno(108);
emp2.setEname("ravi");
emp2.setSalary(8000);
// set childs to parent
//emp1.setDept(); emp2.setDept();
//Save objs
Transaction tx = null;
try {
tx = ses.beginTransaction();
ses.save(emp1);
ses.save(emp2);
tx.commit();
System.out.println(" Employees(childs) and associated parent objs are saved");
} catch (Exception e) {
tx.rollback();
}
}
Main Method
public static void main(String[] args) {
\t \t // Get DAO
\t \t M2ODAO dao=M2ODAOFactory.getDAOInstance();
\t \t //perform persitence operations
\t \t dao.addEmployeesWithDept();
\t \t
\t \t //Close objs
\t \t HibernateUtil.closeSession();
\t \t HibernateUtil.closeSessionFactory();
\t }//main