Manager class
@Table (name= "Jpa_manager") @Entitypublic class Manager {@GeneratedValue @idprivate Integer ID @Column (name= "Manager_ Name ") Private String managername;//a party without a foreign key, does not maintain association relationships//@OneToOne (mappedby=" manager ", Fetch=fetchtype.lazy) @OneToOne ( Mappedby= "Manager")//Do not maintain association relationships, do not recommend modifying fetch properties private Department department;//omit getter Setter}
Department class
@GeneratedValue @idprivate Integer ID, @Column (name= "Department_name") private String departmentname;//generated Jpa_ Department table has foreign KEY constraints @joincolumn (name= "manager_id", unique=true)//1-1 relationship @onetoone (fetch=fetchtype.lazy) Private Manager Manager;//getter Setter}
Test
@Testpublic void testonetoone () {manager manager = new manager (); Manager.setmanagername ("Supervisor 2");D epartment department = new department (); Department.setdepartmentname ("Department 2"); manager.setdepartment (department);d Epartment.setmanager (manager); Entitymanager.persist (manager);//First save the party that does not maintain the association relationship, that is, the party without the foreign Key entitymanager.persist (department);//If you first save the party that maintains the relationship, The UPDATE statement is not recommended//entitymanager.persist (department);//entitymanager.persist (manager);} If a party that maintains an association is acquired, its associated object is acquired through a LEFT outer connection//the load policy can be modified by @onetomany Fetch property @testpublic void testonetoonefind () {department department = entitymanager.find (department.class, 1); System.out.println (Department.getdepartmentname ()); System.out.println (Department.getmanager (). Getmanagername ());} If you get a party that does not maintain an association, it will also get the object through the left Outer connection//You can modify the load policy through the Fetch property of @onetoone, but still send the SQL statement to initialize its associated object//This means that the party that does not maintain the association, modifying fetch Attributes @testpublic void testonetoonefind2 () is not recommended {manager manager = entitymanageR.find (manager.class, 1); System.out.println (Manager.getmanagername ()); System.out.println (Manager.getdepartment (). Getdepartmentname ());}
JPA Learning Notes-mapping bidirectional one-to-one correlation relationships