1 package org.hibernate.test.join; 3 4 import java.util.Iterator ; 5 import java.util.List ; 6 7 import junit.framework.Test; 8 import junit.framework.TestSuite; 9 10 import org.hibernate.Hibernate; 11 import org.hibernate.Session; 12 import org.hibernate.Transaction; 13 import org.hibernate.test.TestCase; 14 15 18 public class JoinTest extends TestCase { 19 20 public JoinTest(String str) { 21 super(str); 22 } 23 24 public void testSequentialSelects() { 25 Session s = openSession(); 26 Transaction t = s.beginTransaction(); 27 28 Employee mark = new Employee(); 29 mark.setName("Mark"); 30 mark.setTitle("internal sales"); 31 mark.setSex('M'); 32 mark.setAddress("buckhead"); 33 mark.setZip("30305"); 34 mark.setCountry("USA"); 35 36 Customer joe = new Customer(); 37 joe.setName("Joe"); 38 joe.setAddress("San Francisco"); 39 joe.setZip("XXXXX"); 40 joe.setCountry("USA"); 41 joe.setComments("Very demanding"); 42 joe.setSex('M'); 43 joe.setSalesperson(mark); 44 45 Person yomomma = new Person(); 46 yomomma.setName("mum"); 47 yomomma.setSex('F'); 48 49 s.save(yomomma); 50 s.save(mark); 51 s.save(joe); 52 53 assertEquals( s.createQuery("from java.io.Serializable").list().size(), 0 ); 54 55 assertEquals( s.createQuery("from Person").list().size(), 3 ); 56 assertEquals( s.createQuery("from Person p where p.class is null").list().size(), 1 ); 57 assertEquals( s.createQuery("from Person p where p.class = Customer").list().size(), 1 ); 58 assertTrue(s.createQuery("from Customer c").list().size()==1); 59 s.clear(); 60 61 List customers = s.createQuery("from Customer c left join fetch c.salesperson").list(); 62 for ( Iterator iter = customers.iterator(); iter.hasNext(); ) { 63 Customer c = (Customer) iter.next(); 64 assertTrue( Hibernate.isInitialized( c.getSalesperson() ) ); 65 assertEquals( c.getSalesperson().getName(), "Mark" ); 66 } 67 assertEquals( customers.size(), 1 ); 68 s.clear(); 69 70 customers = s.createQuery("from Customer").list(); 71 for ( Iterator iter = customers.iterator(); iter.hasNext(); ) { 72 Customer c = (Customer) iter.next(); 73 assertFalse( Hibernate.isInitialized( c.getSalesperson() ) ); 74 assertEquals( c.getSalesperson().getName(), "Mark" ); 75 } 76 assertEquals( customers.size(), 1 ); 77 s.clear(); 78 79 80 mark = (Employee) s.get( Employee.class, new Long ( mark.getId() ) ); 81 joe = (Customer) s.get( Customer.class, new Long ( joe.getId() ) ); 82 83 mark.setZip("30306"); 84 assertEquals( s.createQuery("from Person p where p.zip = '30306'").list().size(), 1 ); 85 s.delete(mark); 86 s.delete(joe); 87 s.delete(yomomma); 88 assertTrue( s.createQuery("from Person").list().isEmpty() ); 89 t.commit(); 90 s.close(); 91 } 92 93 94 protected String [] getMappings() { 95 return new String [] { "join/Person.hbm.xml" }; 96 } 97 98 public static Test suite() { 99 return new TestSuite(JoinTest.class); 100 } 101 102 } 103 104 | Popular Tags |