Manager类
@Table(name="jpa_manager") @Entity public class Manager { @GeneratedValue @Id private Integer id; @Column(name="manager_name") private String managerName; //没有外键的一方,不维护关联关系 // @OneToOne(mappedBy="manager", fetch=FetchType.LAZY) @OneToOne(mappedBy="manager")//不维护关联关系,不建议修改fetch属性 private Department department; //省略getter setter }
Department类
@GeneratedValue @Id private Integer id; @Column(name="department_name") private String departmentName; //生成的jpa_department表中有外键约束 @JoinColumn(name="manager_id", unique=true)//1-1关系 @OneToOne(fetch=FetchType.LAZY) private Manager manager; //getter setter }
测试
@Test public void testOneToOne() { Manager manager = new Manager(); manager.setManagerName("主管2"); Department department = new Department(); department.setDepartmentName("部门2"); manager.setDepartment(department); department.setManager(manager); entityManager.persist(manager);//先保存不维护关联关系的一方,即没有外键的一方 entityManager.persist(department); //若先保存维护关联关系的一方,则会多出update语句,不推荐 // entityManager.persist(department); // entityManager.persist(manager); } //若获取维护关联关系的一方,则会通过左外连接获取其关联的对象 //可以通过@OneToMany的fetch属性来修改加载策略 @Test public void testOneToOneFind() { Department department = entityManager.find(Department.class, 1); System.out.println(department.getDepartmentName()); System.out.println(department.getManager().getManagerName()); } //若获取不维护关联关系的一方,也会通过左外连接获取对象 //可以通过@OneToOne的fetch属性来修改加载策略,但依然会发送SQL语句初始化其关联的对象 //这说明在不维护关联关系的一方,不建议修改fetch属性 @Test public void testOneToOneFind2() { Manager manager = entityManager.find(Manager.class, 1); System.out.println(manager.getManagerName()); System.out.println(manager.getDepartment().getDepartmentName()); }
时间: 2024-10-09 08:30:24