1 package org.hibernate.test.onetoonelink; 3 4 import java.util.Date ; 5 6 import junit.framework.Test; 7 import junit.framework.TestSuite; 8 9 import org.hibernate.Hibernate; 10 import org.hibernate.Session; 11 import org.hibernate.Transaction; 12 import org.hibernate.test.TestCase; 13 14 17 public class OneToOneTest extends TestCase { 18 19 public OneToOneTest(String str) { 20 super(str); 21 } 22 23 public void testOneToOneViaAssociationTable() { 24 Person p = new Person(); 25 p.setName("Gavin King"); 26 p.setDob( new Date () ); 27 Employee e = new Employee(); 28 p.setEmployee(e); 29 e.setPerson(p); 30 31 Session s = openSession(); 32 Transaction t = s.beginTransaction(); 33 s.persist(p); 34 t.commit(); 35 s.close(); 36 37 s = openSession(); 38 t = s.beginTransaction(); 39 e = (Employee) s.createQuery("from Employee e where e.person.name like 'Gavin%'").uniqueResult(); 40 assertEquals( e.getPerson().getName(), "Gavin King" ); 41 assertFalse( Hibernate.isInitialized( e.getPerson() ) ); 42 assertNull( e.getPerson().getCustomer() ); 43 s.clear(); 44 45 e = (Employee) s.createQuery("from Employee e where e.person.dob = :date") 46 .setDate("date", new Date () ) 47 .uniqueResult(); 48 assertEquals( e.getPerson().getName(), "Gavin King" ); 49 assertFalse( Hibernate.isInitialized( e.getPerson() ) ); 50 assertNull( e.getPerson().getCustomer() ); 51 s.clear(); 52 53 t.commit(); 54 s.close(); 55 56 s = openSession(); 57 t = s.beginTransaction(); 58 59 e = (Employee) s.createQuery("from Employee e join fetch e.person p left join fetch p.customer").uniqueResult(); 60 assertTrue( Hibernate.isInitialized( e.getPerson() ) ); 61 assertNull( e.getPerson().getCustomer() ); 62 Customer c = new Customer(); 63 e.getPerson().setCustomer(c); 64 c.setPerson( e.getPerson() ); 65 66 t.commit(); 67 s.close(); 68 69 s = openSession(); 70 t = s.beginTransaction(); 71 72 e = (Employee) s.createQuery("from Employee e join fetch e.person p left join fetch p.customer").uniqueResult(); 73 assertTrue( Hibernate.isInitialized( e.getPerson() ) ); 74 assertTrue( Hibernate.isInitialized( e.getPerson().getCustomer() ) ); 75 assertNotNull( e.getPerson().getCustomer() ); 76 s.delete(e); 77 t.commit(); 78 s.close(); 79 80 } 81 82 protected String [] getMappings() { 83 return new String [] { "onetoonelink/Person.hbm.xml" }; 84 } 85 86 public static Test suite() { 87 return new TestSuite(OneToOneTest.class); 88 } 89 90 } 91 92 | Popular Tags |