員工與部門 ManyToOne 的關係
員工實體
@Entity
public class Employee {
@TableGenerator(name = "employee_gen", table = "id_gen", pkColumnName = "gen_name", valueColumnName = "gen_val", allocationSize = 1)
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "employee_gen")
private int idemployee;
private String firstname;
private String lastname;
private String email;
@ManyToOne
@JoinColumn(name = "iddepartment")
private Department department;
// getters and setters
// toString implementation
}
部門實體
@Entity
public class Department {
@Id
private int iddepartment;
private String name;
// getters, setters and toString()
}
考試班
public class Test {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence
.createEntityManagerFactory("JPAExamples");
EntityManager em = emf.createEntityManager();
EntityTransaction txn = em.getTransaction();
Employee employee = new Employee();
employee.setEmail("someMail@gmail.com");
employee.setFirstname("Prasad");
employee.setLastname("kharkar");
txn.begin();
Department department = em.find(Department.class, 1);//returns the department named vert
System.out.println(department);
txn.commit();
employee.setDepartment(department);
txn.begin();
em.persist(employee);
txn.commit();
}
}