KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > ojb > broker > QueryTest


1 package org.apache.ojb.broker;
2
3 /* Copyright 2002-2005 The Apache Software Foundation
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17
18 import java.sql.Types JavaDoc;
19 import java.util.ArrayList JavaDoc;
20 import java.util.Arrays JavaDoc;
21 import java.util.Collection JavaDoc;
22 import java.util.HashSet JavaDoc;
23 import java.util.Iterator JavaDoc;
24 import java.util.List JavaDoc;
25 import java.util.Set JavaDoc;
26 import java.util.Vector JavaDoc;
27 import java.math.BigDecimal JavaDoc;
28
29 import org.apache.commons.lang.time.StopWatch;
30 import org.apache.ojb.broker.accesslayer.sql.SqlGenerator;
31 import org.apache.ojb.broker.metadata.ClassDescriptor;
32 import org.apache.ojb.broker.metadata.CollectionDescriptor;
33 import org.apache.ojb.broker.platforms.PlatformHsqldbImpl;
34 import org.apache.ojb.broker.query.Criteria;
35 import org.apache.ojb.broker.query.LikeCriteria;
36 import org.apache.ojb.broker.query.Query;
37 import org.apache.ojb.broker.query.QueryByCriteria;
38 import org.apache.ojb.broker.query.QueryFactory;
39 import org.apache.ojb.broker.query.ReportQueryByCriteria;
40 import org.apache.ojb.junit.PBTestCase;
41
42 /**
43  * Testing the query API.
44  * @version $Id: QueryTest.java,v 1.61.2.20 2005/12/21 22:31:23 tomdz Exp $
45  */

46 public class QueryTest extends PBTestCase
47 {
48
49     // Product groups above high water mark are modified by other testcases,
50
// setting this low makes it easier to re-run this test
51
private static final Integer JavaDoc PGROUP_ID_HI_WATERMARK =
52             new Integer JavaDoc(4000);
53     
54     /**
55      * BrokerTests constructor comment.
56      */

57     public QueryTest(String JavaDoc name)
58     {
59         super(name);
60     }
61
62     public static void main(String JavaDoc[] args)
63     {
64         String JavaDoc[] arr = {QueryTest.class.getName()};
65         junit.textui.TestRunner.main(arr);
66     }
67
68     public void testQueryZero()
69     {
70         String JavaDoc name = "testQueryZero_" + System.currentTimeMillis();
71         ObjectRepository.Group group = new ObjectRepository.Group();
72         group.setId(new Integer JavaDoc(0));
73         group.setName(name);
74
75         // prepare test
76
broker.beginTransaction();
77         Query q = QueryFactory.newQuery(group);
78         broker.deleteByQuery(q);
79         broker.commitTransaction();
80         broker.clearCache();
81
82         QueryByCriteria query = new QueryByCriteria(group);
83         ObjectRepository.Group newGroup = (ObjectRepository.Group) broker.getObjectByQuery(query);
84         assertNull(newGroup);
85
86         broker.beginTransaction();
87         broker.store(group);
88         broker.commitTransaction();
89
90         ObjectRepository.Group groupTemp = new ObjectRepository.Group();
91         groupTemp.setId(new Integer JavaDoc(0));
92         Query queryNew = QueryFactory.newQuery(groupTemp);
93         newGroup = (ObjectRepository.Group) broker.getObjectByQuery(queryNew);
94         assertNotNull(newGroup);
95         assertEquals(new Integer JavaDoc(0), newGroup.getId());
96
97         newGroup = (ObjectRepository.Group) broker.getObjectByQuery(queryNew);
98         assertNotNull(newGroup);
99         assertEquals(new Integer JavaDoc(0), newGroup.getId());
100
101         broker.clearCache();
102         newGroup = (ObjectRepository.Group) broker.getObjectByQuery(queryNew);
103         assertNotNull(newGroup);
104         assertEquals(new Integer JavaDoc(0), newGroup.getId());
105     }
106
107     /**
108      * Criteria containing other Criteria only
109      */

110     public void testCriteria()
111     {
112         String JavaDoc name = "testCriteria_" + System.currentTimeMillis();
113         Person p1 = new Person();
114         p1.setFirstname("tomm");
115         p1.setLastname(name);
116
117         Person p2 = new Person();
118         p2.setFirstname("tom");
119         p2.setLastname(name);
120
121         Person p3 = new Person();
122         p3.setFirstname("xtom");
123         p3.setLastname(name);
124
125         broker.beginTransaction();
126         broker.store(p1);
127         broker.store(p2);
128         broker.store(p3);
129         broker.commitTransaction();
130
131         Criteria crit1 = new Criteria();
132         Criteria crit2 = new Criteria();
133         Criteria crit3 = new Criteria();
134
135         crit2.addEqualTo("lastname", name);
136         crit2.setNegative(false);
137
138         crit3.addEqualTo("firstname", "tom");
139         crit3.setNegative(true);
140
141         crit1.addAndCriteria(crit2);
142         crit1.addAndCriteria(crit3);
143
144         Query q = QueryFactory.newQuery(Person.class, crit1);
145         Collection JavaDoc results = broker.getCollectionByQuery(q);
146
147         // all persons except tom
148
assertEquals(2, results.size());
149     }
150
151     /**
152      * test EqualTo Criteria
153      */

154     public void testEqualCriteria()
155     {
156         Criteria crit = new Criteria();
157         crit.addEqualTo("firstname", "tom");
158         Query q = QueryFactory.newQuery(Person.class, crit);
159
160         Collection JavaDoc results = broker.getCollectionByQuery(q);
161         assertNotNull(results);
162         assertTrue(results.size() > 0);
163     }
164
165     /**
166      * test sql Criteria
167      */

168     public void testSqlCriteria()
169     {
170         Criteria crit;
171         Query q;
172         Collection JavaDoc results;
173         
174         // sql only
175
crit = new Criteria();
176         crit.addSql("upper(firstname) = 'TOM' and id = 1");
177         q = QueryFactory.newQuery(Person.class, crit);
178
179         results = broker.getCollectionByQuery(q);
180         int size1 = results.size();
181         
182         // sql plus attribute
183
crit = new Criteria();
184         crit.addSql("upper(firstname) = 'TOM'");
185         crit.addEqualTo("id", new Integer JavaDoc(1));
186         q = QueryFactory.newQuery(Person.class, crit);
187
188         results = broker.getCollectionByQuery(q);
189         int size2 = results.size();
190         
191         // attribute plus sql
192
crit = new Criteria();
193         crit.addEqualTo("upper(firstname)", "TOM");
194         crit.addSql("id = 1");
195         q = QueryFactory.newQuery(Person.class, crit);
196
197         results = broker.getCollectionByQuery(q);
198         int size3 = results.size();
199
200         assertTrue(size2 == size1);
201         assertTrue(size3 == size2);
202     }
203
204
205     /**
206      * test OrderBy and Count
207      */

208     public void testOrderByCount()
209     {
210         Criteria crit = new Criteria();
211         crit.addEqualTo("firstname", "tom");
212         QueryByCriteria q = QueryFactory.newQuery(Person.class, crit);
213         q.addOrderByAscending("firstname");
214
215         Collection JavaDoc results = broker.getCollectionByQuery(q);
216         assertNotNull(results);
217         assertTrue(results.size() > 0);
218         
219         // compare with count
220
int count = broker.getCount(q);
221         assertEquals(results.size(), count);
222     }
223
224     /**
225      * test OrderBy joined column
226      */

227     public void testOrderByJoined()
228     {
229         String JavaDoc name = "testOrderByJoined" + System.currentTimeMillis();
230         Person p = new Person();
231         p.setFirstname("tom");
232         p.setLastname(name);
233
234         Project p1 = new Project();
235         p1.setTitle(name);
236         ArrayList JavaDoc list_1 = new ArrayList JavaDoc();
237         list_1.add(p);
238         p1.setPersons(list_1);
239
240         Project p2 = new Project();
241         p2.setTitle(name);
242         ArrayList JavaDoc list_2 = new ArrayList JavaDoc();
243         list_2.add(p);
244         p2.setPersons(list_2);
245
246         ArrayList JavaDoc list_projects = new ArrayList JavaDoc();
247         list_projects.add(p1);
248         list_projects.add(p2);
249         p.setProjects(list_projects);
250
251         Project p3 = new Project();
252         p3.setTitle(name);
253         ArrayList JavaDoc list_3 = new ArrayList JavaDoc();
254         // empty list
255
p3.setPersons(list_3);
256
257         broker.beginTransaction();
258         broker.store(p1);
259         //broker.store(p2);
260
//broker.store(p3);
261
broker.commitTransaction();
262
263         Criteria crit = new Criteria();
264         crit.addLike("title", name);
265         QueryByCriteria q = QueryFactory.newQuery(Project.class, crit);
266         q.addOrderByAscending("title");
267         q.addOrderByAscending("persons.lastname");
268         q.addOrderByAscending("persons.firstname");
269
270         Collection JavaDoc results = broker.getCollectionByQuery(q);
271         assertNotNull(results);
272         assertEquals(2, results.size());
273
274         // compare with count
275
int count = broker.getCount(q);
276         assertEquals(results.size(), count);
277     }
278
279     /**
280      * test Subquery get all product groups without articles
281      * <p/>
282      * test may fail if db does not support sub queries
283      */

284     public void testSubQuery2()
285     {
286         Collection JavaDoc results = null;
287         String JavaDoc stamp = "" + System.currentTimeMillis();
288         int loops = 10;
289         // create ProductGroups without article
290
broker.beginTransaction();
291         for(int i = 0; i < loops; i++)
292         {
293             ProductGroup pg = new ProductGroup();
294             pg.setGroupName("test group " + stamp);
295             pg.setDescription("build by QueryTest#testSubQuery2");
296             broker.store(pg);
297         }
298         broker.commitTransaction();
299
300         ReportQueryByCriteria subQuery;
301         Criteria subCrit = new Criteria();
302         Criteria crit = new Criteria();
303
304         subQuery = QueryFactory.newReportQuery(Article.class, subCrit);
305         subQuery.setAttributes(new String JavaDoc[]{"productGroupId"});
306         subQuery.setDistinct(true);
307
308         crit.addEqualTo("groupName", "test group " + stamp);
309         crit.addNotIn("groupId", subQuery);
310         Query q = QueryFactory.newQuery(ProductGroup.class, crit);
311
312         results = broker.getCollectionByQuery(q);
313         assertNotNull(results);
314         assertEquals("Result of the query with sub-query does not match", loops, results.size());
315     }
316
317     /**
318      * test Subquery get all articles with price > avg(price) PROBLEM:
319      * avg(price) is NOT extent aware !!
320      * <p/>
321      * test may fail if db does not support sub queries
322      */

323     public void testSubQuery1()
324     {
325
326         ReportQueryByCriteria subQuery;
327         Criteria subCrit = new Criteria();
328         Criteria crit = new Criteria();
329
330         subCrit.addLike("articleName", "A%");
331         subQuery = QueryFactory.newReportQuery(Article.class, subCrit);
332         subQuery.setAttributes(new String JavaDoc[]{"avg(price)"});
333
334         crit.addGreaterOrEqualThan("price", subQuery);
335         Query q = QueryFactory.newQuery(Article.class, crit);
336
337         Collection JavaDoc results = broker.getCollectionByQuery(q);
338         assertNotNull(results);
339         assertTrue(results.size() > 0);
340
341     }
342
343     /**
344      * test Subquery get all product groups with more than 10 articles, uses
345      * attribute as value ! see testSubQuery4 for a better way
346      * <p/>
347      * test may fail if db does not support sub queries
348      */

349     public void testSubQuery3()
350     {
351
352         ReportQueryByCriteria subQuery;
353         Criteria subCrit = new Criteria();
354         Criteria crit = new Criteria();
355
356         subCrit.addEqualToField("productGroupId", Criteria.PARENT_QUERY_PREFIX + "groupId");
357         subQuery = QueryFactory.newReportQuery(Article.class, subCrit);
358         subQuery.setAttributes(new String JavaDoc[]{"count(productGroupId)"});
359
360         crit.addLessThan("10", subQuery); // MORE than 10 articles, uses
361
// attribute as value !
362
crit.addLessThan("groupId", PGROUP_ID_HI_WATERMARK);
363         Query q = QueryFactory.newQuery(ProductGroup.class, crit);
364
365         Collection JavaDoc results = broker.getCollectionByQuery(q);
366         assertNotNull(results);
367         assertEquals(4, results.size());
368     }
369
370     /**
371      * test Subquery get all product groups with more than 10 articles
372      * <p/>
373      * test may fail if db does not support sub queries
374      */

375     public void testSubQuery4()
376     {
377
378         ReportQueryByCriteria subQuery;
379         Criteria subCrit = new Criteria();
380         Criteria crit = new Criteria();
381
382         subCrit.addEqualToField("productGroupId", Criteria.PARENT_QUERY_PREFIX + "groupId");
383         subQuery = QueryFactory.newReportQuery(Article.class, subCrit);
384         subQuery.setAttributes(new String JavaDoc[]{"count(productGroupId)"});
385
386         // mkalen: if using String("10") instead of Integer below,
387
// PostgreSQL will return 7 (sic!) groups
388
crit.addGreaterThan(subQuery, new Integer JavaDoc(10)); // MORE than 10 articles
389
crit.addLessThan("groupId", PGROUP_ID_HI_WATERMARK);
390         Query q = QueryFactory.newQuery(ProductGroup.class, crit);
391
392         Collection JavaDoc results = broker.getCollectionByQuery(q);
393         assertNotNull(results);
394         assertEquals(4, results.size());
395     }
396
397     /**
398      * test Like Criteria
399      */

400     public void testLikeCriteria()
401     {
402
403         Criteria crit = new Criteria();
404         crit.addLike("firstname", "%o%");
405         Query q = QueryFactory.newQuery(Person.class, crit);
406
407         Collection JavaDoc results = broker.getCollectionByQuery(q);
408         assertNotNull(results);
409         assertTrue(results.size() > 0);
410
411         // compare with count
412
int count = broker.getCount(q);
413         assertEquals(results.size(), count);
414     }
415
416     /**
417      * test escaped Like Criteria
418      */

419     public void testLikeEscapedCriteria1()
420     {
421         Criteria crit = new Criteria();
422         crit.addLike("firstname", "h%\\%");
423         Query q = QueryFactory.newQuery(Person.class, crit);
424
425         Collection JavaDoc results = broker.getCollectionByQuery(q);
426         assertNotNull(results);
427         assertEquals(1, results.size());
428
429         // compare with count
430
int count = broker.getCount(q);
431         assertEquals(results.size(), count);
432     }
433
434     /**
435      * test escaped Like Criteria with escape character
436      */

437     public void testLikeEscapedCriteria2()
438     {
439         LikeCriteria.setEscapeCharacter('|');
440
441         Criteria crit = new Criteria();
442         crit.addLike("firstname", "h%|%");
443         Query q = QueryFactory.newQuery(Person.class, crit);
444
445         Collection JavaDoc results = broker.getCollectionByQuery(q);
446         assertNotNull(results);
447         assertEquals(1, results.size());
448
449         // compare with count
450
int count = broker.getCount(q);
451         assertEquals(results.size(), count);
452     }
453
454     /**
455      * test escaped Like Criteria
456      */

457     public void testLikeEscapedCriteria3()
458     {
459         String JavaDoc name = "testLikeEscapedCriteria3()_" + System.currentTimeMillis();
460         Person p = new Person();
461         p.setFirstname("123%45");
462         p.setLastname(name);
463         broker.beginTransaction();
464         broker.store(p);
465         broker.commitTransaction();
466
467         LikeCriteria.setEscapeCharacter('/');
468         Criteria crit = new Criteria();
469         crit.addEqualTo("lastname", name);
470         crit.addLike("firstname", "%/%45");
471         Query q = QueryFactory.newQuery(Person.class, crit);
472
473         Collection JavaDoc results = broker.getCollectionByQuery(q);
474         assertNotNull(results);
475         assertEquals(1, results.size());
476     }
477
478     /**
479      * test Null Criteria
480      */

481     public void testNullCriteria()
482     {
483         String JavaDoc name = "testNullCriteria_" + System.currentTimeMillis();
484         Person p = new Person();
485         p.setLastname(name);
486         broker.beginTransaction();
487         broker.store(p);
488         broker.commitTransaction();
489
490         Criteria crit = new Criteria();
491         crit.addIsNull("firstname");
492         Criteria crit2 = new Criteria();
493         crit2.addLike("lastname", name);
494         crit.addAndCriteria(crit2);
495         
496         Query q = QueryFactory.newQuery(Person.class, crit);
497
498         Collection JavaDoc results = broker.getCollectionByQuery(q);
499         assertNotNull(results);
500         assertEquals(1, results.size());
501     }
502
503     /**
504      * Add an empty criteria
505      */

506     public void testEmptyORed() throws Exception JavaDoc
507     {
508         Collection JavaDoc result;
509         Criteria crit1 = new Criteria();
510         crit1.addEqualTo("articleName", "Hamlet");
511         crit1.addEqualTo("productGroup.description", "Strange Books...");
512
513         Criteria crit2 = new Criteria();
514
515         crit1.addOrCriteria(crit2);
516         QueryByCriteria q = QueryFactory.newQuery(Article.class, crit1);
517
518         result = broker.getCollectionByQuery(q);
519         assertNotNull(result);
520
521         int count = broker.getCount(q);
522         assertEquals(count, result.size());
523     }
524
525     /**
526      * Add an empty criteria
527      */

528     public void testEmptyANDed() throws Exception JavaDoc
529     {
530         Collection JavaDoc result;
531         Criteria crit1 = new Criteria();
532         crit1.addEqualTo("articleName", "Hamlet");
533         crit1.addEqualTo("productGroup.description", "Strange Books...");
534
535         Criteria crit2 = new Criteria();
536
537         crit1.addAndCriteria(crit2);
538         QueryByCriteria q = QueryFactory.newQuery(Article.class, crit1);
539
540         result = broker.getCollectionByQuery(q);
541         assertNotNull(result);
542
543         int count = broker.getCount(q);
544         assertEquals(count, result.size());
545     }
546
547     /**
548      * test Between Criteria
549      */

550     public void testBetweenCriteria()
551     {
552
553         Criteria crit = new Criteria();
554         crit.addBetween("id", new Integer JavaDoc(1), new Integer JavaDoc(5));
555         Query q = QueryFactory.newQuery(Person.class, crit);
556
557         Collection JavaDoc results = broker.getCollectionByQuery(q);
558         assertNotNull(results);
559         assertTrue(results.size() == 5);
560
561         // compare with count
562
int count = broker.getCount(q);
563         assertEquals(results.size(), count);
564     }
565
566     /**
567      * test In Criteria
568      */

569     public void testInCriteria()
570     {
571
572         Criteria crit = new Criteria();
573         Collection JavaDoc ids = new Vector JavaDoc();
574         ids.add(new Integer JavaDoc(1));
575         ids.add(new Integer JavaDoc(3));
576         ids.add(new Integer JavaDoc(5));
577
578         crit.addIn("id", ids);
579         Query q = QueryFactory.newQuery(Person.class, crit);
580
581         Collection JavaDoc results = broker.getCollectionByQuery(q);
582         assertNotNull(results);
583         assertTrue(results.size() == 3);
584
585         // compare with count
586
int count = broker.getCount(q);
587         assertEquals(results.size(), count);
588     }
589
590     /**
591      * Single Path Expression
592      */

593     public void testPathExpressions()
594     {
595
596         Criteria crit = new Criteria();
597         crit.addEqualTo("productGroup.groupName", "Liquors");
598         Query q = QueryFactory.newQuery(Article.class, crit);
599
600         Collection JavaDoc results = broker.getCollectionByQuery(q);
601         assertNotNull(results);
602         assertTrue(results.size() > 0);
603
604         // compare with count
605
int count = broker.getCount(q);
606         assertEquals(results.size(), count);
607     }
608
609     /**
610      * Multi Path Expression over decomposed m:n
611      */

612     public void testPathExpressionsMtoNDecomposed()
613     {
614
615         Criteria crit = new Criteria();
616         crit.addEqualTo("roles.project.title", "HSQLDB");
617         // use decomposed m:n
618
Query q = QueryFactory.newQuery(Person.class, crit);
619
620         Collection JavaDoc results = broker.getCollectionByQuery(q);
621         assertNotNull(results);
622
623     }
624
625     /**
626      * Multi Path Expression over nondecomposed m:n
627      */

628     public void testPathExpressionsMtoN()
629     {
630
631         Criteria crit = new Criteria();
632         crit.addEqualTo("projects.title", "HSQLDB"); // direct m:n
633
Query q = QueryFactory.newQuery(Person.class, crit);
634
635         Collection JavaDoc results = broker.getCollectionByQuery(q);
636         assertNotNull(results);
637
638     }
639
640     /**
641      * Multi Path Expression over nondecomposed m:n new test case for the 'not
642      * unique alias' problem with m:n relationship
643      */

644     public void testPathExpressionsMtoN2()
645     {
646         Criteria crit = new Criteria();
647         crit.addEqualTo("projects.roles.roleName", "developer");
648         crit.addLike("projects.persons.lastname", "%b%");
649         Query q = QueryFactory.newQuery(Person.class, crit);
650
651         Collection JavaDoc results = broker.getCollectionByQuery(q);
652         assertNotNull(results);
653         assertTrue(results.size() > 0);
654     }
655
656     /**
657      * Distinct Query
658      */

659     public void testDistinct()
660     {
661
662         Criteria crit = new Criteria();
663         crit.addLike("allArticlesInGroup.articleName", "C%");
664         QueryByCriteria q = QueryFactory.newQuery(ProductGroup.class, crit, true);
665         q.addOrderByAscending("groupId");
666
667         Collection JavaDoc results = broker.getCollectionByQuery(q);
668         assertNotNull(results);
669         assertEquals(5, results.size());
670
671         // compare with count
672
int count = broker.getCount(q);
673         assertEquals(results.size(), count);
674     }
675
676     /**
677      * Distinct Query
678      */

679     public void testDistinctMultiPk()
680     {
681
682         Criteria crit = new Criteria();
683         crit.addEqualTo("project_id", new Integer JavaDoc(1));
684         QueryByCriteria q = QueryFactory.newQuery(Role.class, crit, true);
685
686         Collection JavaDoc results = broker.getCollectionByQuery(q);
687         assertNotNull(results);
688         assertEquals(3, results.size());
689
690         // compare with count
691
int count = broker.getCount(q);
692
693         assertEquals(results.size(), count); // FAILS
694
}
695
696     /**
697      * Simple ReportQuery returning rows with 3 columns of Person
698      */

699     public void testReportQuery()
700     {
701         String JavaDoc name = "testReportQuery_" + System.currentTimeMillis();
702         Person p1 = new Person();
703         p1.setFirstname("Robert");
704         p1.setLastname(name);
705         Person p2 = new Person();
706         p2.setFirstname("Tom");
707         p2.setLastname(name);
708         Person p3 = new Person();
709         p3.setFirstname("Roger");
710         p3.setLastname(name);
711         broker.beginTransaction();
712         broker.store(p1);
713         broker.store(p2);
714         broker.store(p3);
715         broker.commitTransaction();
716
717
718         Criteria crit = new Criteria();
719         Collection JavaDoc results = new Vector JavaDoc();
720         crit.addLike("firstname", "%o%");
721         Criteria crit2 = new Criteria();
722         crit2.addLike("lastname", name);
723         crit.addAndCriteria(crit2);
724         ReportQueryByCriteria q = QueryFactory.newReportQuery(Person.class, crit);
725         q.setAttributes(new String JavaDoc[]{"id", "firstname", "count(*)"});
726         q.addGroupBy(new String JavaDoc[]{"id", "firstname"});
727
728         Iterator JavaDoc iter = broker.getReportQueryIteratorByQuery(q);
729
730         assertNotNull(iter);
731         while(iter.hasNext())
732         {
733             Object JavaDoc[] row = (Object JavaDoc[]) iter.next();
734             assertEquals(3, row.length);
735
736             results.add(row);
737         }
738
739         assertEquals(3, results.size());
740
741         // compare with count
742
int count = broker.getCount(q);
743         assertEquals(results.size(), count);
744     }
745
746     /**
747      * Simple ReportQuery returning rows with max(id) of Person grouped by not selected columns
748      */

749     public void testReportQueryGroupByNonSelectColumns()
750     {
751         String JavaDoc name = "testReportQueryGroupByNonSelectColumns_" + System.currentTimeMillis();
752         Person p1 = new Person();
753         p1.setFirstname("Robert");
754         p1.setLastname(name);
755         Person p2 = new Person();
756         p2.setFirstname("Tom");
757         p2.setLastname(name);
758         Person p3 = new Person();
759         p3.setFirstname("Roger");
760         p3.setLastname(name);
761         broker.beginTransaction();
762         broker.store(p1);
763         broker.store(p2);
764         broker.store(p3);
765         broker.commitTransaction();
766
767         Criteria crit = new Criteria();
768         Collection JavaDoc results = new Vector JavaDoc();
769         crit.addLike("firstname", "%o%");
770         Criteria crit2 = new Criteria();
771         crit2.addLike("lastname", name);
772         crit.addAndCriteria(crit2);
773         ReportQueryByCriteria q = QueryFactory.newReportQuery(Person.class, crit);
774         q.setAttributes(new String JavaDoc[]{"max(id)"});
775         q.addGroupBy(new String JavaDoc[]{"lastname", "firstname"});
776
777         Iterator JavaDoc iter = broker.getReportQueryIteratorByQuery(q);
778
779         assertNotNull(iter);
780         while(iter.hasNext())
781         {
782             Object JavaDoc[] row = (Object JavaDoc[]) iter.next();
783             assertEquals(1, row.length);
784
785             results.add(row);
786         }
787
788         assertEquals(3, results.size());
789
790         // compare with count
791
int count = broker.getCount(q);
792         assertEquals(results.size(), count);
793     }
794
795     /**
796      * Simple ReportQuery returning rows with 3 columns of Person
797      * Type of column data defined by sqltypes
798      *
799      * @see java.sql.Types
800      */

801     public void testReportQueryWithJdbcTypes()
802     {
803         String JavaDoc name = "testReportQuery_" + System.currentTimeMillis();
804         Person p1 = new Person();
805         p1.setFirstname("Robert");
806         p1.setLastname(name);
807         Person p2 = new Person();
808         p2.setFirstname("Tom");
809         p2.setLastname(name);
810         Person p3 = new Person();
811         p3.setFirstname("Roger");
812         p3.setLastname(name);
813         broker.beginTransaction();
814         broker.store(p1);
815         broker.store(p2);
816         broker.store(p3);
817         broker.commitTransaction();
818
819         int types[] = new int[]{Types.DECIMAL, Types.VARCHAR, Types.BIGINT};
820         Criteria crit = new Criteria();
821         Collection JavaDoc results = new Vector JavaDoc();
822         crit.addLike("firstname", "%o%");
823         Criteria crit2 = new Criteria();
824         crit2.addLike("lastname", name);
825         crit.addAndCriteria(crit2);
826
827         ReportQueryByCriteria q = QueryFactory.newReportQuery(Person.class, crit);
828         q.setAttributes(new String JavaDoc[]{"id", "firstname", "count(*)"});
829         q.addGroupBy(new String JavaDoc[]{"id", "firstname"});
830         q.setJdbcTypes(types);
831
832         Iterator JavaDoc iter = broker.getReportQueryIteratorByQuery(q);
833
834         assertNotNull(iter);
835         while(iter.hasNext())
836         {
837             Object JavaDoc[] row = (Object JavaDoc[]) iter.next();
838             assertEquals(3, row.length);
839
840 // assertEquals(row[0].getClass(), BigDecimal.class);
841
// assertEquals(row[1].getClass(), String.class);
842
// assertEquals(row[2].getClass(), Long.class);
843

844             results.add(row);
845         }
846
847         assertEquals(3, results.size());
848
849     }
850
851     /**
852      * Simple ReportQuery returning rows with 3 columns of Person
853      * needs SQL paging
854      */

855     public void testReportQueryWithStartAndEnd()
856     {
857         Criteria crit = new Criteria();
858         Collection JavaDoc results = new Vector JavaDoc();
859         crit.addLike("firstname", "%o%");
860         ReportQueryByCriteria q = QueryFactory.newReportQuery(Person.class, crit);
861         q.setAttributes(new String JavaDoc[]{"id", "firstname", "count(*)"});
862         q.addGroupBy(new String JavaDoc[]{"id", "firstname"});
863
864         q.setStartAtIndex(3);
865         q.setEndAtIndex(5);
866         Iterator JavaDoc iter = broker.getReportQueryIteratorByQuery(q);
867         assertNotNull(iter);
868         while(iter.hasNext())
869         {
870             results.add(iter.next());
871         }
872         assertTrue(results.size() == 3);
873
874         results.clear();
875         q.setStartAtIndex(1);
876         q.setEndAtIndex(5);
877         iter = broker.getReportQueryIteratorByQuery(q);
878         assertNotNull(iter);
879         while(iter.hasNext())
880         {
881             results.add(iter.next());
882         }
883         assertTrue(results.size() == 5);
884     }
885
886     /**
887      * Simple ReportQuery returning rows with 2 columns of Person
888      */

889     public void testReportQueryExtent()
890     {
891
892         Criteria crit = new Criteria();
893         Collection JavaDoc results = new Vector JavaDoc();
894         crit.addLike("articleName", "%o%");
895         ReportQueryByCriteria q = QueryFactory.newReportQuery(Article.class, crit);
896         q.setAttributes(new String JavaDoc[]{"articleId", "articleName", "price"});
897
898         Iterator JavaDoc iter = broker.getReportQueryIteratorByQuery(q);
899
900         assertNotNull(iter);
901         while(iter.hasNext())
902         {
903             results.add(iter.next());
904         }
905         assertTrue(results.size() > 0);
906
907         // compare with count
908
int count = broker.getCount(q);
909         assertEquals(results.size(), count);
910     }
911
912     /**
913      * Concrete Class in SubQuery
914      */

915     public void testSubQueryAgainstConcreteClass()
916     {
917         String JavaDoc name = "testSubQueryAgainstConcreteClass_" + System.currentTimeMillis();
918         Article article = new BookArticle();
919         article.setArticleName(name);
920         ProductGroup group = new ProductGroup();
921         group.setGroupName(name);
922         article.setProductGroup(group);
923
924         broker.beginTransaction();
925         broker.store(group);
926         broker.store(article);
927         broker.commitTransaction();
928
929         Criteria critMain = new Criteria();
930         Criteria critSub = new Criteria();
931
932         critSub.addEqualTo("articleName", name);
933         ReportQueryByCriteria querySub = QueryFactory.newReportQuery(BookArticle.class, critSub);
934         querySub.setAttributes(new String JavaDoc[]{"productGroupId"});
935
936         ReportQueryByCriteria queryMain = QueryFactory.newReportQuery(AbstractProductGroup.class, critMain);
937         queryMain.setAttributes(new String JavaDoc[]{"groupId", "groupName"});
938         critMain.addIn("groupId", querySub);
939
940         Iterator JavaDoc iter = broker.getReportQueryIteratorByQuery(queryMain);
941         int result = 0;
942         assertNotNull(iter);
943         while(iter.hasNext())
944         {
945             iter.next();
946             ++result;
947         }
948         assertEquals(1, result);
949
950         // compare with count
951
int count = broker.getCount(queryMain);
952         assertEquals(result, count);
953     }
954
955     /**
956      * Class with extents in SubQuery.
957      * SubQueries are NOT extent aware ! so we have to use two queries.
958      */

959     public void testSubQueryAgainstExtents()
960     {
961         String JavaDoc name = "testSubQueryAgainstExtents_" + System.currentTimeMillis();
962         Article article = new BookArticle();
963         article.setArticleName(name);
964         ProductGroup group = new ProductGroup();
965         group.setGroupName(name);
966         article.setProductGroup(group);
967
968         broker.beginTransaction();
969         broker.store(group);
970         broker.store(article);
971         broker.commitTransaction();
972
973         Criteria critMain = new Criteria();
974         Criteria critSub = new Criteria();
975
976         critSub.addEqualTo("articleName", name);
977         ReportQueryByCriteria querySub = QueryFactory.newReportQuery(Article.class, critSub);
978         querySub.setAttributes(new String JavaDoc[]{"productGroupId"});
979         Iterator JavaDoc subIter = broker.getReportQueryIteratorByQuery(querySub);
980         Collection JavaDoc subIds = new ArrayList JavaDoc();
981         while(subIter.hasNext())
982         {
983             Object JavaDoc[] id = (Object JavaDoc[]) subIter.next();
984             subIds.add(id[0]);
985         }
986
987         ReportQueryByCriteria queryMain = QueryFactory.newReportQuery(AbstractProductGroup.class, critMain);
988         queryMain.setAttributes(new String JavaDoc[]{"groupId", "groupName"});
989         critMain.addIn("groupId", subIds);
990
991         Iterator JavaDoc iter = broker.getReportQueryIteratorByQuery(queryMain);
992         int result = 0;
993         assertNotNull(iter);
994         while(iter.hasNext())
995         {
996             iter.next();
997             ++result;
998         }
999         assertEquals(1, result);
1000    
1001        // compare with count
1002
int count = broker.getCount(queryMain);
1003        assertEquals(result, count);
1004    }
1005
1006    /**
1007     * ReportQuery with pathExpression in columns
1008     */

1009    public void testReportQueryPathExpression()
1010    {
1011        Criteria crit = new Criteria();
1012        Collection JavaDoc results = new Vector JavaDoc();
1013        crit.addLike("articleName", "C%");
1014        ReportQueryByCriteria q = QueryFactory.newReportQuery(Article.class, crit);
1015        q.setAttributes(new String JavaDoc[]{"productGroup.groupName", "articleId", "articleName", "price"});
1016
1017        Iterator JavaDoc iter = broker.getReportQueryIteratorByQuery(q);
1018
1019        assertNotNull(iter);
1020        while(iter.hasNext())
1021        {
1022            results.add(iter.next());
1023        }
1024        assertEquals(9, results.size());
1025
1026        // compare with count
1027
int count = broker.getCount(q);
1028        assertEquals(results.size(), count);
1029
1030    }
1031
1032    /**
1033     * ReportQuery returning rows with some "Liquor" data ordered by price
1034     */

1035    public void testReportQueryOrderBy()
1036    {
1037
1038        Criteria crit = new Criteria();
1039        Collection JavaDoc results = new Vector JavaDoc();
1040        crit.addEqualTo("productGroup.groupName", "Liquors");
1041        ReportQueryByCriteria q = QueryFactory.newReportQuery(Article.class, crit);
1042        q.setAttributes(new String JavaDoc[]{"articleId", "articleName", "price"});
1043        q.addOrderByAscending("price");
1044
1045        Iterator JavaDoc iter = broker.getReportQueryIteratorByQuery(q);
1046        assertNotNull(iter);
1047        while(iter.hasNext())
1048        {
1049            results.add(iter.next());
1050        }
1051        assertTrue(results.size() > 0);
1052
1053        // compare with count
1054
int count = broker.getCount(q);
1055        assertEquals(results.size(), count);
1056
1057    }
1058
1059    /**
1060     * ReportQuery returning rows with some "Liquor" data ordered by productGroup.groupId
1061     */

1062    public void testReportQueryOrderByNonSelectColumn()
1063    {
1064
1065        Criteria crit = new Criteria();
1066        Collection JavaDoc results = new Vector JavaDoc();
1067        crit.addEqualTo("productGroup.groupName", "Liquors");
1068        ReportQueryByCriteria q = QueryFactory.newReportQuery(Article.class, crit);
1069        q.setAttributes(new String JavaDoc[]{"articleId", "articleName", "price"});
1070        q.addOrderByAscending("productGroup.groupId");
1071
1072        Iterator JavaDoc iter = broker.getReportQueryIteratorByQuery(q);
1073        assertNotNull(iter);
1074        while(iter.hasNext())
1075        {
1076            results.add(iter.next());
1077        }
1078        assertTrue(results.size() > 0);
1079
1080        // compare with count
1081
int count = broker.getCount(q);
1082        assertEquals(results.size(), count);
1083
1084    }
1085
1086    /**
1087     * ReportQuery returning rows with summed stock and price per article group
1088     * The selected columns point to a class having extents.<br>
1089     * The query produces a wrong sql, selecting only rows of the top-class
1090     */

1091    public void testReportQueryGroupByExtents2()
1092    {
1093        Criteria crit = new Criteria();
1094        Collection JavaDoc results = new Vector JavaDoc();
1095        ReportQueryByCriteria q = QueryFactory.newReportQuery(ProductGroup.class, crit);
1096        q.setAttributes(new String JavaDoc[]{"groupName", "sum(allArticlesInGroup.stock)", "sum(allArticlesInGroup.price)"});
1097        q.addGroupBy("groupName");
1098
1099        Iterator JavaDoc iter = broker.getReportQueryIteratorByQuery(q);
1100        
1101// SELECT A0.KategorieName,sum(A1.Lagerbestand),sum(A1.Einzelpreis)
1102
// FROM Kategorien A0
1103
// LEFT OUTER JOIN artikel A1 ON A0.Kategorie_Nr=A1.Kategorie_Nr
1104
// LEFT OUTER JOIN books A1E2 ON A0.Kategorie_Nr=A1E2.Kategorie_Nr
1105
// LEFT OUTER JOIN cds A1E1 ON A0.Kategorie_Nr=A1E1.Kategorie_Nr
1106
// GROUP BY A0.KategorieName
1107

1108        assertNotNull(iter);
1109        while(iter.hasNext())
1110        {
1111            results.add(iter.next());
1112        }
1113        assertTrue(results.size() > 0);
1114
1115        // TODO: resolve
1116
if (ojbSkipKnownIssueProblem("broker.getCount() vs .getReportQueryIteratorByQuery().size()"))
1117        {
1118            return;
1119        }
1120
1121        // compare with count
1122
int count = broker.getCount(q);
1123        assertEquals(results.size(), count); // FAILS !
1124
}
1125
1126    /**
1127     * ReportQuery returning rows with summed stock and price per article group
1128     * The selected class has the extents.<br>
1129     * The query returns summed values for each row, so there may be multiple rows
1130     * for one productgroup because one query for each extent is executed.
1131     */

1132    public void testReportQueryGroupByExtents1()
1133    {
1134        Criteria crit = new Criteria();
1135        Collection JavaDoc results = new Vector JavaDoc();
1136        ReportQueryByCriteria q = QueryFactory.newReportQuery(Article.class, crit);
1137        q.setAttributes(new String JavaDoc[]{"productGroup.groupName", "sum(stock)", "sum(price)"});
1138        q.addGroupBy("productGroup.groupName");
1139
1140        Iterator JavaDoc iter = broker.getReportQueryIteratorByQuery(q);
1141        
1142// SELECT A1.KategorieName,sum(A0.Lagerbestand),sum(A0.Einzelpreis)
1143
// FROM artikel A0
1144
// INNER JOIN Kategorien A1 ON A0.Kategorie_Nr=A1.Kategorie_Nr
1145
// GROUP BY A1.KategorieName
1146
//
1147
// SELECT A1.KategorieName,sum(A0.Lagerbestand),sum(A0.Einzelpreis)
1148
// FROM cds A0
1149
// INNER JOIN Kategorien A1 ON A0.Kategorie_Nr=A1.Kategorie_Nr
1150
// GROUP BY A1.KategorieName
1151
//
1152
// SELECT A1.KategorieName,sum(A0.Lagerbestand),sum(A0.Einzelpreis)
1153
// FROM books A0
1154
// INNER JOIN Kategorien A1 ON A0.Kategorie_Nr=A1.Kategorie_Nr
1155
// GROUP BY A1.KategorieName
1156

1157        assertNotNull(iter);
1158        while(iter.hasNext())
1159        {
1160            results.add(iter.next());
1161        }
1162        assertTrue(results.size() > 0);
1163
1164        // TODO: resolve
1165
if (ojbSkipKnownIssueProblem("broker.getCount() vs .getReportQueryIteratorByQuery().size()"))
1166        {
1167            return;
1168        }
1169        
1170        // compare with count
1171
int count = broker.getCount(q);
1172        assertEquals(results.size(), count); // FAILS !
1173
}
1174
1175    /**
1176     * Read a CD and then read the ProductGroup for the CD
1177     */

1178    public void testInversePathExpression()
1179    {
1180        QueryByCriteria query;
1181        Criteria crit;
1182        CdArticle cd;
1183        ProductGroupProxy pg, cdPg;
1184
1185        crit = new Criteria();
1186        crit.addEqualTo("articleId", new Integer JavaDoc(200));
1187        query = new QueryByCriteria(CdArticle.class, crit);
1188        cd = (CdArticle) broker.getObjectByQuery(query);
1189        cdPg = (ProductGroupProxy) cd.getProductGroup();
1190
1191        crit = new Criteria();
1192        crit.addEqualTo("allArticlesInGroup.articleId", cd.getArticleId());
1193        query = new QueryByCriteria(ProductGroup.class, crit);
1194        query.setPathClass("allArticlesInGroup", CdArticle.class);
1195        pg = (ProductGroupProxy) broker.getObjectByQuery(query);
1196
1197        // this test can only succeed in singlevm mode:
1198
// if (!BrokerHelper.isRunningInServerMode())
1199
// {
1200
// assertNotNull(pg);
1201
// assertNotNull(cdPg);
1202
// assertEquals("ProductGroups should be identical", pg.getRealSubject().toString(), cdPg.getRealSubject().toString());
1203
// }
1204

1205        assertNotNull(pg);
1206        assertNotNull(cdPg);
1207        assertEquals("ProductGroups should be identical", pg.getRealSubject().toString(), cdPg.getRealSubject().toString());
1208    }
1209
1210    /**
1211     * prefetch Articles for ProductGroupsWithArray, Does not yet work with
1212     * Arrays
1213     */

1214    public void testPrefetchedArraySingleKey()
1215    {
1216        ClassDescriptor cldArticle = broker.getClassDescriptor(Article.class);
1217        Class JavaDoc articleProxy = cldArticle.getProxyClass();
1218
1219        //
1220
// use ProductGroup and Articles with disabled Proxy
1221
//
1222
broker.clearCache();
1223        cldArticle.setProxyClass(null);
1224
1225        Criteria crit = new Criteria();
1226        crit.addLessOrEqualThan("groupId", new Integer JavaDoc(5));
1227        QueryByCriteria q = QueryFactory.newQuery(ProductGroupWithArray.class, crit);
1228        q.addOrderByDescending("groupId");
1229        q.addPrefetchedRelationship("allArticlesInGroup");
1230
1231        Collection JavaDoc results = broker.getCollectionByQuery(q);
1232        assertNotNull(results);
1233        assertTrue(results.size() > 0);
1234        ProductGroupWithArray pg = (ProductGroupWithArray) results.toArray()[0];
1235        int articleSize = pg.getAllArticles().length;
1236        assertTrue(articleSize != 0);
1237        String JavaDoc articleString = Arrays.asList(pg.getAllArticles()).toString();
1238
1239        //
1240
// use ProductGroupWithArray and Articles with original Proxy settings
1241
//
1242
broker.clearCache();
1243        cldArticle.setProxyClass(articleProxy);
1244
1245
1246        crit = new Criteria();
1247        crit.addEqualTo("groupId", new Integer JavaDoc(5));
1248        q = QueryFactory.newQuery(ProductGroupWithArray.class, crit);
1249        results = broker.getCollectionByQuery(q);
1250        ProductGroupWithArray pg2 = (ProductGroupWithArray) results.toArray()[0];
1251        InterfaceArticle[] articles = pg2.getAllArticles();
1252        assertNotNull("Array of articles should not be null!", articles);
1253        assertTrue("Array should contain more than 0 entries!", articles.length != 0);
1254
1255        // force materialization
1256
for(int i = 0; i < articles.length; i++)
1257        {
1258            articles[i].getArticleName();
1259        }
1260        int articleSize2 = articles.length;
1261        String JavaDoc articleString2 = Arrays.asList(articles).toString();
1262
1263        //
1264
// compare prefetched and 'normal' data
1265
//
1266
assertEquals("Check size", articleSize, articleSize2);
1267        assertEquals("Check content", articleString, articleString2);
1268
1269    }
1270
1271    /**
1272     * orderby for prefetch Articles of ProductGroups
1273     */

1274    public void testPrefetchedCollectionOrderBy()
1275    {
1276        ClassDescriptor cldProductGroup = broker.getClassDescriptor(ProductGroup.class);
1277        ClassDescriptor cldArticle = broker.getClassDescriptor(Article.class);
1278        Class JavaDoc productGroupProxy = cldProductGroup.getProxyClass();
1279        Class JavaDoc articleProxy = cldArticle.getProxyClass();
1280        CollectionDescriptor cds = cldProductGroup.getCollectionDescriptorByName("allArticlesInGroup");
1281
1282        //
1283
// use ProductGroup and Articles with disabled Proxy
1284
//
1285
cldProductGroup.setProxyClass(null);
1286        cldProductGroup.setProxyClassName(null);
1287        cldArticle.setProxyClass(null);
1288        cldArticle.setProxyClassName(null);
1289        broker.getDescriptorRepository().setClassDescriptor(cldProductGroup);
1290        broker.getDescriptorRepository().setClassDescriptor(cldArticle);
1291        
1292        //
1293
// orderby articleId, ASC
1294
//
1295
broker.clearCache();
1296        cds.getOrderBy().clear();
1297        cds.addOrderBy("articleId", true);
1298         
1299        Criteria crit = new Criteria();
1300        crit.addLessOrEqualThan("groupId", new Integer JavaDoc(5));
1301        QueryByCriteria q = QueryFactory.newQuery(ProductGroup.class, crit);
1302        q.addOrderByDescending("groupId");
1303        q.addPrefetchedRelationship("allArticlesInGroup");
1304
1305        Collection JavaDoc results = broker.getCollectionByQuery(q);
1306        assertNotNull(results);
1307        assertTrue(results.size() == 5);
1308        InterfaceProductGroup pg = (InterfaceProductGroup) results.toArray()[1];
1309        assertNotNull(pg.getAllArticles());
1310        Object JavaDoc articles[] = pg.getAllArticles().toArray();
1311        int articleSize = articles.length;
1312        assertTrue(articleSize == 10);
1313        Article a1 = (Article) articles[0];
1314        Article a2 = (Article) articles[9];
1315        assertTrue(a1.getArticleId().intValue() < a2.getArticleId().intValue());
1316
1317        //
1318
// orderby articleId, DESC
1319
//
1320
broker.clearCache();
1321        cds.getOrderBy().clear();
1322        cds.addOrderBy("articleId", false);
1323
1324        results = broker.getCollectionByQuery(q);
1325        assertNotNull(results);
1326        assertTrue(results.size() == 5);
1327        pg = (InterfaceProductGroup) results.toArray()[1];
1328        assertNotNull(pg.getAllArticles());
1329        articles = pg.getAllArticles().toArray();
1330        articleSize = articles.length;
1331        assertTrue(articleSize == 10);
1332        Article b1 = (Article) articles[0];
1333        Article b2 = (Article) articles[9];
1334        assertTrue(b1.getArticleId().intValue() > b2.getArticleId().intValue());
1335
1336        assertEquals(a1.getArticleId(), b2.getArticleId());
1337        assertEquals(a2.getArticleId(), b1.getArticleId());
1338
1339        //
1340
// use ProductGroup and Articles with original Proxy settings
1341
//
1342
cldProductGroup.setProxyClass(productGroupProxy);
1343        cldProductGroup.setProxyClassName(productGroupProxy.getName());
1344        cldArticle.setProxyClass(articleProxy);
1345        cldArticle.setProxyClassName(articleProxy.getName());
1346        broker.getDescriptorRepository().setClassDescriptor(cldProductGroup);
1347        broker.getDescriptorRepository().setClassDescriptor(cldArticle);
1348   }
1349
1350    /**
1351     * prefetch Articles for ProductGroups
1352     */

1353    public void testPrefetchedCollectionSingleKey()
1354    {
1355        ClassDescriptor cldProductGroup = broker.getClassDescriptor(ProductGroup.class);
1356        ClassDescriptor cldArticle = broker.getClassDescriptor(Article.class);
1357        Class JavaDoc productGroupProxy = cldProductGroup.getProxyClass();
1358        Class JavaDoc articleProxy = cldArticle.getProxyClass();
1359
1360        //
1361
// use ProductGroup and Articles with disabled Proxy
1362
//
1363
broker.clearCache();
1364        cldProductGroup.setProxyClass(null);
1365        cldProductGroup.setProxyClassName(null);
1366        cldArticle.setProxyClass(null);
1367        cldArticle.setProxyClassName(null);
1368        broker.getDescriptorRepository().setClassDescriptor(cldProductGroup);
1369        broker.getDescriptorRepository().setClassDescriptor(cldArticle);
1370
1371        Criteria crit = new Criteria();
1372        crit.addLessOrEqualThan("groupId", new Integer JavaDoc(5));
1373        QueryByCriteria q = QueryFactory.newQuery(ProductGroup.class, crit);
1374        q.addOrderByDescending("groupId");
1375        q.addPrefetchedRelationship("allArticlesInGroup");
1376
1377        Collection JavaDoc results = broker.getCollectionByQuery(q);
1378        assertNotNull(results);
1379        assertTrue(results.size() > 0);
1380        InterfaceProductGroup pg = (InterfaceProductGroup) results.toArray()[0];
1381        assertNotNull(pg.getAllArticles());
1382        int articleSize = pg.getAllArticles().size();
1383        String JavaDoc articleString = pg.getAllArticles().toString();
1384
1385        //
1386
// use ProductGroup and Articles with original Proxy settings
1387
//
1388
broker.clearCache();
1389        cldProductGroup.setProxyClass(productGroupProxy);
1390        cldProductGroup.setProxyClassName(productGroupProxy.getName());
1391        cldArticle.setProxyClass(articleProxy);
1392        cldArticle.setProxyClassName(articleProxy.getName());
1393        broker.getDescriptorRepository().setClassDescriptor(cldProductGroup);
1394        broker.getDescriptorRepository().setClassDescriptor(cldArticle);
1395
1396        crit = new Criteria();
1397        crit.addEqualTo("groupId", new Integer JavaDoc(5));
1398        q = QueryFactory.newQuery(ProductGroup.class, crit);
1399        results = broker.getCollectionByQuery(q);
1400        InterfaceProductGroup pg2 = (InterfaceProductGroup) results.toArray()[0];
1401        // force materialization
1402
for(Iterator JavaDoc it = pg2.getAllArticles().iterator(); it.hasNext();)
1403        {
1404            ((InterfaceArticle) it.next()).getArticleName();
1405        }
1406        int articleSize2 = pg2.getAllArticles().size();
1407        String JavaDoc articleString2 = pg2.getAllArticles().toString();
1408
1409        //
1410
// compare prefetched and 'normal' data
1411
//
1412
assertEquals("Check size", articleSize, articleSize2);
1413        assertEquals("Check content", articleString, articleString2);
1414    }
1415
1416    /**
1417     * Test nested joins using pathExpressions
1418     */

1419    public void testNestedJoins()
1420    {
1421        ArrayList JavaDoc list = new java.util.ArrayList JavaDoc();
1422
1423        Criteria crit = new Criteria();
1424        ReportQueryByCriteria q = QueryFactory.newReportQuery(Person.class, crit, true);
1425
1426        q.setAttributes(new String JavaDoc[]{"roles.roleName", "roles.project.title", "firstname", });
1427
1428        Iterator JavaDoc iter = broker.getReportQueryIteratorByQuery(q);
1429        while(iter.hasNext())
1430        {
1431            list.add(iter.next());
1432        }
1433
1434        assertTrue(list.size() > 0);
1435    }
1436
1437    /**
1438     * Test multiple non nested joins using pathExpressions
1439     */

1440    public void testMultipleJoins()
1441    {
1442        ArrayList JavaDoc list = new java.util.ArrayList JavaDoc();
1443
1444        Criteria crit = new Criteria();
1445        ReportQueryByCriteria q = QueryFactory.newReportQuery(Role.class, crit, true);
1446
1447        q.setAttributes(new String JavaDoc[]{"roleName", "project.title", "person.firstname", });
1448
1449        Iterator JavaDoc iter = broker.getReportQueryIteratorByQuery(q);
1450        while(iter.hasNext())
1451        {
1452            list.add(iter.next());
1453        }
1454
1455        assertTrue(list.size() > 0);
1456    }
1457
1458    /**
1459     * Test nested joins using pathExpressions *** Fails under hsqldb because
1460     * of join using multiple keys ***
1461     */

1462    public void tesXNestedJoins2()
1463    {
1464        ArrayList JavaDoc list = new ArrayList JavaDoc();
1465        Criteria crit = new Criteria();
1466        ReportQueryByCriteria q = QueryFactory.newReportQuery(Task.class, crit);
1467
1468        q.setAttributes(new String JavaDoc[]{"role.roleName", "role.project.title", "role.person.firstname", });
1469
1470        Iterator JavaDoc iter = broker.getReportQueryIteratorByQuery(q);
1471        while(iter.hasNext())
1472        {
1473            list.add(iter.next());
1474        }
1475        assertTrue(list.size() > 0);
1476    }
1477
1478    /**
1479     * prefetch ProductGroups for Articles
1480     */

1481    public void testPrefetchedReferencesSingleKey()
1482    {
1483        ClassDescriptor cldProductGroup = broker.getClassDescriptor(ProductGroup.class);
1484        ClassDescriptor cldArticle = broker.getClassDescriptor(Article.class);
1485        Class JavaDoc productGroupProxy = cldProductGroup.getProxyClass();
1486        Class JavaDoc articleProxy = cldArticle.getProxyClass();
1487
1488        //
1489
// use ProductGroup and Articles with disabled Proxy
1490
//
1491
broker.clearCache();
1492        cldProductGroup.setProxyClass(null);
1493        cldProductGroup.setProxyClassName(null);
1494        cldArticle.setProxyClass(null);
1495        cldArticle.setProxyClassName(null);
1496        broker.getDescriptorRepository().setClassDescriptor(cldProductGroup);
1497        broker.getDescriptorRepository().setClassDescriptor(cldArticle);
1498
1499        Criteria crit = new Criteria();
1500        crit.addNotNull("productGroupId");
1501        crit.addLessOrEqualThan("productGroupId", new Integer JavaDoc(5));
1502        QueryByCriteria q = QueryFactory.newQuery(Article.class, crit);
1503        q.addOrderByDescending("productGroupId");
1504        q.addPrefetchedRelationship("productGroup");
1505
1506        Collection JavaDoc results = broker.getCollectionByQuery(q);
1507        Set JavaDoc pgs = new HashSet JavaDoc();
1508        Iterator JavaDoc iter = results.iterator();
1509        while(iter.hasNext())
1510        {
1511            InterfaceArticle a = (InterfaceArticle) iter.next();
1512            pgs.add(a.getProductGroup().getName());
1513        }
1514
1515        assertTrue(pgs.size() > 0);
1516        String JavaDoc pgsString = pgs.toString();
1517
1518        //
1519
// use ProductGroup and Articles with original Proxy settings
1520
//
1521
broker.clearCache();
1522        cldProductGroup.setProxyClass(productGroupProxy);
1523        cldProductGroup.setProxyClassName(productGroupProxy.getName());
1524        cldArticle.setProxyClass(articleProxy);
1525        cldArticle.setProxyClassName(articleProxy.getName());
1526        broker.getDescriptorRepository().setClassDescriptor(cldProductGroup);
1527        broker.getDescriptorRepository().setClassDescriptor(cldArticle);
1528
1529        crit = new Criteria();
1530        crit.addNotNull("productGroupId");
1531        crit.addLessOrEqualThan("productGroupId", new Integer JavaDoc(5));
1532        q = QueryFactory.newQuery(Article.class, crit);
1533        q.addOrderByDescending("productGroupId");
1534
1535        results = broker.getCollectionByQuery(q);
1536        Set JavaDoc pgs2 = new HashSet JavaDoc();
1537        iter = results.iterator();
1538        while(iter.hasNext())
1539        {
1540            InterfaceArticle a = (InterfaceArticle) iter.next();
1541            pgs2.add(a.getProductGroup().getName());
1542        }
1543
1544        assertTrue(pgs2.size() > 0);
1545        String JavaDoc pgsString2 = pgs2.toString();
1546
1547        //
1548
// compare prefetched and 'normal' data
1549
//
1550
assertEquals("Check size", pgs.size(), pgs2.size());
1551        assertEquals("Check content", pgsString, pgsString2);
1552
1553    }
1554
1555    /**
1556     * test PathExpression pointing to abstract class (InterfaceArticle)
1557     */

1558    public void testReportPathExpressionAbstractExtent()
1559    {
1560        // TODO: make path expressions extent aware
1561
if(ojbSkipKnownIssueProblem("Make path expressions extent aware")) return;
1562
1563        ArrayList JavaDoc list = new ArrayList JavaDoc();
1564        Criteria crit = new Criteria();
1565        crit.addEqualTo("groupId", new Integer JavaDoc(5));
1566
1567        ReportQueryByCriteria q = QueryFactory.newReportQuery(ProductGroupWithAbstractArticles.class, crit, true);
1568        q.setAttributes(new String JavaDoc[]{"groupId", "groupName", "allArticlesInGroup.articleId", "allArticlesInGroup.articleName"});
1569
1570        Iterator JavaDoc iter = broker.getReportQueryIteratorByQuery(q);
1571        while(iter.hasNext())
1572        {
1573            list.add(iter.next());
1574        }
1575
1576        // 7 Articles, 2 Books, 3 Cds
1577
// BRJ: path expression is not yet extent aware
1578
assertEquals("check size", 12, list.size());
1579    }
1580
1581    /**
1582     * ReportQuery returning rows with some "Liquor" data ordered by productGroup.groupId
1583     */

1584    public void testQueryOrderByNonSelectColumn()
1585    {
1586
1587        Criteria crit = new Criteria();
1588        Collection JavaDoc results = new Vector JavaDoc();
1589        crit.addEqualTo("productGroup.groupName", "Liquors");
1590        QueryByCriteria q = QueryFactory.newQuery(Article.class, crit);
1591        q.addOrderByAscending("productGroup.groupId");
1592
1593        Iterator JavaDoc iter = broker.getIteratorByQuery(q);
1594        assertNotNull(iter);
1595        while(iter.hasNext())
1596        {
1597            results.add(iter.next());
1598        }
1599        assertTrue(results.size() > 0);
1600
1601    }
1602
1603    /**
1604     * test PathExpression pointing to abstract class (InterfaceArticle)
1605     */

1606    public void testPathExpressionForAbstractExtent()
1607    {
1608        ArrayList JavaDoc list = new java.util.ArrayList JavaDoc();
1609
1610        Criteria crit = new Criteria();
1611        crit.addLike("allArticlesInGroup.articleName", "Chef%");
1612        Criteria crit1 = new Criteria();
1613        crit1.addEqualTo("allArticlesInGroup.articleName", "Faust");
1614        crit.addOrCriteria(crit1);
1615
1616        QueryByCriteria q = QueryFactory.newQuery(ProductGroupWithAbstractArticles.class, crit, true);
1617        q.addOrderByAscending("groupId");
1618
1619        Iterator JavaDoc iter = broker.getIteratorByQuery(q);
1620        while(iter.hasNext())
1621        {
1622            list.add(iter.next());
1623        }
1624
1625        // Groups 2, 5
1626
assertEquals("check size", 2, list.size());
1627
1628        assertEquals("Group 2", 2, ((InterfaceProductGroup) list.get(0)).getId().intValue());
1629        assertEquals("Group 5", 5, ((InterfaceProductGroup) list.get(1)).getId().intValue());
1630    }
1631
1632    /**
1633     * Test pathExpression and Extents
1634     */

1635    public void testReportPathExpressionForExtents1()
1636    {
1637        ArrayList JavaDoc list = new java.util.ArrayList JavaDoc();
1638
1639        Criteria crit = new Criteria();
1640        crit.addGreaterOrEqualThan("allArticlesInGroup.articleId", new Integer JavaDoc(1));
1641        crit.addLessOrEqualThan("allArticlesInGroup.articleId", new Integer JavaDoc(5));
1642
1643        ReportQueryByCriteria q = QueryFactory.newReportQuery(ProductGroup.class, crit, true);
1644        q.setAttributes(new String JavaDoc[]{"groupId", "groupName", "allArticlesInGroup.articleId"});
1645
1646        Iterator JavaDoc iter = broker.getReportQueryIteratorByQuery(q);
1647        while(iter.hasNext())
1648        {
1649            Object JavaDoc row;
1650            Object JavaDoc[] columns;
1651
1652            assertNotNull("Invalid ReportQueryIterator, hasNext() is true but next() is null",
1653                    row = iter.next());
1654            assertTrue("ReportQuery result row is not Object[]",
1655                    row instanceof Object JavaDoc[]);
1656            columns = (Object JavaDoc[]) row;
1657            list.add(columns);
1658
1659            assertTrue("ReportQuery result row does not contain all expected columns",
1660                    columns.length == 3);
1661
1662            /*
1663            arminw:
1664            think hsql returns the wrong result or interpret the query in wrong
1665            way (e.g. using hashcode of values instead values itself), so skip test
1666            evaluation for this DB
1667            */

1668            if(!broker.serviceConnectionManager().getSupportedPlatform().getClass().equals(PlatformHsqldbImpl.class))
1669            {
1670// System.out.println("### " + ((Object[]) obj)[0]
1671
// + " " + ((Object[]) obj)[1]
1672
// + " " + ((Object[]) obj)[2]);
1673
Object JavaDoc articleId = columns[2];
1674                int i = -1;
1675                if (articleId instanceof Integer JavaDoc) {
1676                    i = ((Integer JavaDoc) articleId).intValue();
1677                } else if (articleId instanceof BigDecimal JavaDoc) {
1678                    i = ((BigDecimal JavaDoc) articleId).intValue();
1679                } else {
1680                    assertTrue("TODO: Your platforms resulting class for INTEGER (" +
1681                                articleId.getClass().getName() +
1682                                ") is not yet supported in testcase.", false);
1683                }
1684
1685                assertTrue("i=" + i, i < 6 & i > 0);
1686            }
1687        }
1688    }
1689
1690    /**
1691     * Test pathExpression and Extents
1692     */

1693    public void testReportPathExpressionForExtents2()
1694    {
1695        ArrayList JavaDoc list = new java.util.ArrayList JavaDoc();
1696
1697        Criteria crit = new Criteria();
1698        crit.addLike("groupName", "%o%");
1699        crit.addLike("allArticlesInGroup.articleName", "%\u00f6%"); //unicode for �
1700

1701        ReportQueryByCriteria q = QueryFactory.newReportQuery(ProductGroup.class, crit, true);
1702        q.setAttributes(new String JavaDoc[]{"groupId", "groupName"});
1703
1704        Iterator JavaDoc iter = broker.getReportQueryIteratorByQuery(q);
1705        while(iter.hasNext())
1706        {
1707            list.add(iter.next());
1708        }
1709
1710        // Groups: 3 Books , 1 Dairy Product
1711
assertEquals("check size", 2, list.size());
1712    }
1713
1714    /**
1715     * ReportQuery with Expression in column need to add table alias to the field (price)
1716     **/

1717    public void testReportQueryExpressionInStatement()
1718    {
1719        // TODO: Resolve attributes of expressions
1720
if(ojbSkipKnownIssueProblem("Resolve attributes of expressions")) return;
1721
1722        Criteria crit = new Criteria();
1723        ReportQueryByCriteria q = QueryFactory.newReportQuery(Article.class, crit);
1724        q.setAttributes(new String JavaDoc[]{"articleId", "price+10"});
1725        ClassDescriptor cd = broker.getClassDescriptor(q.getBaseClass());
1726        SqlGenerator sqlg = broker.serviceSqlGenerator();
1727        String JavaDoc sql = sqlg.getPreparedSelectStatement(q, cd).getStatement();
1728        
1729        assertTrue("Bad query generated. the 'price' field has not table prefix. SQL Output: " + sql, sql
1730                .equalsIgnoreCase("SELECT A0.Artikel_Nr,A0.Einzelpreis+10 FROM Artikel A0"));
1731    }
1732     
1733
1734    /**
1735     * Test pathExpression and Extents
1736     */

1737    public void testPathExpressionForExtents1()
1738    {
1739        ArrayList JavaDoc list = new java.util.ArrayList JavaDoc();
1740
1741        Criteria crit = new Criteria();
1742        crit.addEqualTo("allArticlesInGroup.productGroupId", new Integer JavaDoc(5));
1743
1744        Query q = QueryFactory.newQuery(ProductGroup.class, crit, true);
1745
1746        Iterator JavaDoc iter = broker.getIteratorByQuery(q);
1747        while(iter.hasNext())
1748        {
1749            list.add(iter.next());
1750        }
1751
1752        // ProductGroup 5
1753
assertEquals("check size", 1, list.size());
1754    }
1755
1756    /**
1757     * Test pathExpression and Extents
1758     */

1759    public void testPathExpressionForExtents2()
1760    {
1761        ArrayList JavaDoc list = new java.util.ArrayList JavaDoc();
1762
1763        Criteria crit = new Criteria();
1764        crit.addLike("upper(allArticlesInGroup.articleName)", "F%");
1765
1766        Query q = QueryFactory.newQuery(ProductGroup.class, crit, true);
1767
1768        Iterator JavaDoc iter = broker.getIteratorByQuery(q);
1769        while(iter.hasNext())
1770        {
1771            list.add(iter.next());
1772        }
1773
1774        // ProductGroups 4 and 5
1775
assertEquals("check size", 2, list.size());
1776
1777    }
1778
1779    /**
1780     * Test pathExpression and Extents musicians is only defined in CD
1781     */

1782    public void testPathExpressionForExtents3()
1783    {
1784        ArrayList JavaDoc list = new java.util.ArrayList JavaDoc();
1785
1786        Criteria crit = new Criteria();
1787        crit.addLike("allArticlesInGroup.musicians", "%");
1788
1789        QueryByCriteria q = QueryFactory.newQuery(ProductGroup.class, crit, true);
1790        q.setPathClass("allArticlesInGroup", CdArticle.class);
1791
1792        Iterator JavaDoc iter = broker.getIteratorByQuery(q);
1793        while(iter.hasNext())
1794        {
1795            list.add(iter.next());
1796        }
1797
1798        // ProductGroups 5
1799
assertEquals("check size", 1, list.size());
1800    }
1801
1802    /**
1803     * Test pathExpression and Extents Abstract Base
1804     */

1805    public void testPathExpressionForExtents4()
1806    {
1807        ArrayList JavaDoc list = new java.util.ArrayList JavaDoc();
1808
1809        Criteria crit = new Criteria();
1810        crit.addEqualTo("allArticlesInGroup.productGroupId", new Integer JavaDoc(5));
1811
1812        Query q = QueryFactory.newQuery(AbstractProductGroup.class, crit, true);
1813
1814        Iterator JavaDoc iter = broker.getIteratorByQuery(q);
1815        while(iter.hasNext())
1816        {
1817            list.add(iter.next());
1818        }
1819
1820        // ProductGroup 5
1821
assertEquals("check size", 1, list.size());
1822    }
1823
1824    /**
1825     * Test pathExpression and Extents using Alias
1826     */

1827    public void testPathExpressionForExtentsAlias()
1828    {
1829        ArrayList JavaDoc list = new java.util.ArrayList JavaDoc();
1830
1831        Criteria crit1 = new Criteria();
1832        crit1.setAlias("NAMES");
1833        crit1.addLike("upper(allArticlesInGroup.articleName)", "F%");
1834
1835        Criteria crit2 = new Criteria();
1836        crit2.addGreaterOrEqualThan("allArticlesInGroup.stock", new Integer JavaDoc(110));
1837
1838        crit1.addAndCriteria(crit2);
1839        Query q = QueryFactory.newQuery(ProductGroup.class, crit1, true);
1840
1841        Iterator JavaDoc iter = broker.getIteratorByQuery(q);
1842        while(iter.hasNext())
1843        {
1844            list.add(iter.next());
1845        }
1846
1847        // ProductGroup 4
1848
assertEquals("check size", 1, list.size());
1849    }
1850
1851    /**
1852     * Test ReportQuery and Alias
1853     */

1854    public void testReportQueryAlias()
1855    {
1856        ArrayList JavaDoc list = new java.util.ArrayList JavaDoc();
1857
1858        Criteria crit1 = new Criteria();
1859        crit1.setAlias("NAMES");
1860        crit1.addLike("upper(allArticlesInGroup.articleName)", "F%");
1861
1862        Criteria crit2 = new Criteria();
1863        crit2.setAlias("STOCKS");
1864        crit2.addGreaterOrEqualThan("allArticlesInGroup.stock", new Integer JavaDoc(110));
1865
1866        crit1.addAndCriteria(crit2);
1867        ReportQueryByCriteria q = QueryFactory.newReportQuery(ProductGroup.class, crit1);
1868        q.setAttributes(new String JavaDoc[]{"groupId", "groupName", "STOCKS.allArticlesInGroup.articleName",
1869                                     "NAMES.allArticlesInGroup.articleName", "NAMES.allArticlesInGroup.stock"});
1870
1871        // Due to AliasPrefixes ArticleName is taken from A2 and A1, Stock from A1,
1872
// SELECT A0.Kategorie_Nr,A0.KategorieName,A2.Artikelname,A1.Artikelname,A1.Lagerbestand FROM
1873

1874        Iterator JavaDoc iter = broker.getReportQueryIteratorByQuery(q);
1875        while(iter.hasNext())
1876        {
1877            list.add(iter.next());
1878        }
1879
1880        // ProductGroup 4 with it's Articles
1881
assertEquals("check size", 1, list.size());
1882    }
1883
1884    /**
1885     * Run a query range test that includes one record less than the total
1886     * number of records that exist.
1887     */

1888    public void testQueryRangeOneLessThanTotal()
1889    {
1890        this.runQueryRangeTest(-1);
1891    }
1892
1893    /**
1894     * Run a query range test that includes all of the records that exist.
1895     */

1896    public void testQueryRangeAllRecords()
1897    {
1898        this.runQueryRangeTest(0);
1899    }
1900
1901    /**
1902     * Run a query range test.
1903     */

1904    public void testQueryRangeMassTest()
1905    {
1906        String JavaDoc name = "testQueryRangeMassTest_" + System.currentTimeMillis();
1907        int objCount = 2000;
1908
1909        broker.beginTransaction();
1910        for(int i = 0; i < objCount; i++)
1911        {
1912            Gourmet a = new Gourmet();
1913            a.setName(name);
1914            broker.store(a);
1915        }
1916        broker.commitTransaction();
1917
1918        Criteria crit = new Criteria();
1919        crit.addEqualTo("name", name);
1920        QueryByCriteria q = QueryFactory.newQuery(Gourmet.class, crit);
1921        q.setStartAtIndex(100);
1922        q.setEndAtIndex(109);
1923
1924        StopWatch watch = new StopWatch();
1925        watch.start();
1926        Collection JavaDoc c = broker.getCollectionByQuery(q);
1927        watch.stop();
1928        System.out.println("# Query 10 of " + objCount + " objects take " + watch.getTime() + " ms");
1929        assertNotNull(c);
1930        List JavaDoc result = new ArrayList JavaDoc(c);
1931        assertEquals(10, result.size());
1932
1933        crit = new Criteria();
1934        crit.addEqualTo("name", name);
1935        q = QueryFactory.newQuery(Gourmet.class, crit);
1936        watch.reset();
1937        watch.start();
1938        c = broker.getCollectionByQuery(q);
1939        watch.stop();
1940        System.out.println("# Query all " + objCount + " objects take " + watch.getTime() + " ms");
1941        assertNotNull(c);
1942        result = new ArrayList JavaDoc(c);
1943        assertEquals(objCount, result.size());
1944
1945        broker.beginTransaction();
1946        for(int i = 0; i < result.size(); i++)
1947        {
1948            broker.delete(result.get(i));
1949        }
1950        broker.commitTransaction();
1951
1952        c = broker.getCollectionByQuery(q);
1953        assertNotNull(c);
1954        result = new ArrayList JavaDoc(c);
1955        assertEquals(0, result.size());
1956    }
1957
1958    /**
1959     * Run a query range test that includes one record more than the total
1960     * number of records that exist.
1961     */

1962    public void testQueryRangeOneMoreThanTotal()
1963    {
1964        this.runQueryRangeTest(+1);
1965    }
1966
1967    /**
1968     * Run a query range test.
1969     *
1970     * @param delta the amount to add to the existing record count when setting
1971     * the start/end index for the query that we'll use.
1972     */

1973    private void runQueryRangeTest(int delta)
1974    {
1975
1976        // How many records are there in the table?
1977
Query countQuery = QueryFactory.newQuery(ProductGroup.class, null, false);
1978
1979        // Get the existing record count
1980
int recordCount = broker.getCollectionByQuery(countQuery).toArray().length;
1981
1982        // Build a query that will get the range we're looking for.
1983
Query listQuery = QueryFactory.newQuery(ProductGroup.class, null, false);
1984        listQuery.setStartAtIndex(1);
1985        listQuery.setEndAtIndex(recordCount + delta);
1986
1987        // Get the list.
1988
Object JavaDoc[] theObjects = broker.getCollectionByQuery(listQuery).toArray();
1989
1990        // Verify the record count
1991
if(delta <= 0)
1992        {
1993            assertEquals("record count", (recordCount + delta), theObjects.length);
1994        }
1995        else
1996        {
1997            assertEquals("record count", recordCount, theObjects.length);
1998        }
1999
2000        // Verify the query size, fullSize is 0
2001
// assertEquals("Query size", recordCount, listQuery.fullSize());
2002
}
2003
2004    public void testQueryMN_Alias1() throws Exception JavaDoc
2005    {
2006        Criteria crit1 = new Criteria();
2007        Criteria crit2 = new Criteria();
2008        QueryByCriteria q;
2009        Collection JavaDoc result;
2010
2011        broker.clearCache();
2012
2013        // get persons working for projects OJB and SODA
2014
crit1.addLike("projects.title", "OJB%");
2015        crit1.setAlias("alias1");
2016        crit2.addLike("projects.title", "SODA%");
2017        crit2.setAlias("alias2");
2018        crit1.addAndCriteria(crit2);
2019
2020        q = QueryFactory.newQuery(Person.class, crit1, true);
2021        result = broker.getCollectionByQuery(q);
2022        assertNotNull(result);
2023        assertTrue(result.size() == 2); // bob, tom
2024
}
2025
2026    public void testQueryMN_Alias2() throws Exception JavaDoc
2027    {
2028        Criteria crit1 = new Criteria();
2029        Criteria crit2 = new Criteria();
2030        QueryByCriteria q;
2031        Collection JavaDoc result1;
2032        Collection JavaDoc result2;
2033
2034        broker.clearCache();
2035
2036        // get persons working for projects OJB (alias should have no effect)
2037
crit1.setAlias("myAlias");
2038        crit1.addLike("firstname", "%o%");
2039        crit1.addLike("projects.title", "OJB%");
2040
2041        q = QueryFactory.newQuery(Person.class, crit1, true);
2042        result1 = broker.getCollectionByQuery(q);
2043        assertNotNull(result1);
2044        assertTrue(result1.size() == 2); // bob, tom
2045

2046        // WITHOUT ALIAS
2047
// get persons working for projects OJB
2048
crit2.addLike("firstname", "%o%");
2049        crit2.addLike("projects.title", "OJB%");
2050
2051        q = QueryFactory.newQuery(Person.class, crit2, true);
2052        result2 = broker.getCollectionByQuery(q);
2053        assertNotNull(result2);
2054        assertTrue(result2.size() == 2); // bob, tom
2055

2056    }
2057
2058    public void testQueryMN() throws Exception JavaDoc
2059    {
2060        Criteria crit1 = new Criteria();
2061        Criteria crit2 = new Criteria();
2062        QueryByCriteria q;
2063        Collection JavaDoc result;
2064
2065        broker.clearCache();
2066
2067        // get persons working for projects OJB _or_ SODA
2068
crit1.addLike("projects.title", "OJB%");
2069        crit2.addLike("projects.title", "SODA%");
2070        crit1.addOrCriteria(crit2);
2071
2072        q = QueryFactory.newQuery(Person.class, crit1, true);
2073        result = broker.getCollectionByQuery(q);
2074        assertNotNull(result);
2075        assertTrue(result.size() == 5); // bob, tom, cindy, albert ,betrand
2076
}
2077
2078    public void testQueryCommutative12() throws Exception JavaDoc
2079    {
2080        Collection JavaDoc result;
2081        Criteria crit1 = new Criteria();
2082        crit1.addEqualTo("articleName", "Hamlet");
2083        crit1.addEqualTo("productGroup.description", "Strange Books...");
2084
2085        Criteria crit2 = new Criteria();
2086        crit2.addEqualTo("stock", new Integer JavaDoc(32));
2087
2088        Criteria crit3 = new Criteria();
2089        crit3.addEqualTo("stock", new Integer JavaDoc(42));
2090
2091        crit2.addOrCriteria(crit3);
2092        crit1.addAndCriteria(crit2);
2093        QueryByCriteria qry12 = QueryFactory.newQuery(Article.class, crit1);
2094        qry12.setPathOuterJoin("productGroup");
2095
2096        result = broker.getCollectionByQuery(qry12);
2097        assertNotNull(result);
2098
2099        int count = broker.getCount(qry12);
2100        assertEquals(count, result.size());
2101    }
2102
2103
2104    public void testQueryCommutative21()
2105    {
2106        Collection JavaDoc result;
2107        Criteria crit1 = new Criteria();
2108        crit1.addEqualTo("articleName", "Hamlet");
2109        crit1.addEqualTo("productGroup.description", "Strange Books...");
2110
2111        Criteria crit2 = new Criteria();
2112        crit2.addEqualTo("stock", new Integer JavaDoc(32));
2113
2114        Criteria crit3 = new Criteria();
2115        crit3.addEqualTo("stock", new Integer JavaDoc(42));
2116
2117        crit2.addOrCriteria(crit3);
2118        crit2.addAndCriteria(crit1);
2119        QueryByCriteria qry21 = QueryFactory.newQuery(Article.class, crit2);
2120        qry21.setPathOuterJoin("productGroup");
2121
2122        result = broker.getCollectionByQuery(qry21);
2123        assertNotNull(result);
2124
2125        int count = broker.getCount(qry21);
2126        assertEquals(count, result.size());
2127    }
2128
2129    public void testOuterJoin()
2130    {
2131        Article a = new Article();
2132        a.articleName = "Good stuff";
2133        a.productGroup = null;
2134        broker.beginTransaction();
2135        broker.store(a);
2136        broker.commitTransaction();
2137        
2138        Criteria crit = new Criteria();
2139        crit.addLike("articleName", "G%");
2140        crit.addIsNull("productGroup.description");
2141        
2142        QueryByCriteria qry1 = QueryFactory.newQuery(Article.class, crit);
2143        Collection JavaDoc result1 = broker.getCollectionByQuery(qry1);
2144
2145        QueryByCriteria qry2 = QueryFactory.newQuery(Article.class, crit);
2146        qry2.setPathOuterJoin("productGroup");
2147        Collection JavaDoc result2 = broker.getCollectionByQuery(qry2);
2148        
2149        assertEquals(0, result1.size());
2150        assertEquals(1, result2.size());
2151        
2152        broker.beginTransaction();
2153        broker.delete(a);
2154        broker.commitTransaction();
2155    }
2156    
2157    public void testExtentByInterface()
2158    {
2159        String JavaDoc name = "testExtentByInterface_" + System.currentTimeMillis();
2160        Zoo zoo = new Zoo();
2161        zoo.setName(name);
2162        Mammal m1 = new Mammal();
2163        m1.setName(name);
2164        Mammal m2 = new Mammal();
2165        m2.setName(name);
2166        Reptile r1 = new Reptile();
2167        r1.setName(name);
2168        broker.beginTransaction();
2169        broker.store(zoo);
2170        m1.setZooId(zoo.getZooId());
2171        m2.setZooId(zoo.getZooId());
2172        r1.setZooId(zoo.getZooId());
2173        broker.store(m1);
2174        broker.store(m2);
2175        broker.store(r1);
2176        broker.commitTransaction();
2177
2178        Criteria crit = new Criteria();
2179        crit.addEqualTo("name", name);
2180
2181        QueryByCriteria queryAnimals = QueryFactory.newQuery(InterfaceAnimal.class, crit);
2182        QueryByCriteria queryReptile = QueryFactory.newQuery(Reptile.class, crit);
2183        QueryByCriteria queryMammal = QueryFactory.newQuery(Mammal.class, crit);
2184
2185        Collection JavaDoc resultA = broker.getCollectionByQuery(queryAnimals);
2186        Collection JavaDoc resultR = broker.getCollectionByQuery(queryReptile);
2187        Collection JavaDoc resultM = broker.getCollectionByQuery(queryMammal);
2188
2189        assertEquals(3, resultA.size());
2190        assertEquals(1, resultR.size());
2191        assertEquals(2, resultM.size());
2192
2193        for(Iterator JavaDoc iterator = resultA.iterator(); iterator.hasNext();)
2194        {
2195            InterfaceAnimal a = (InterfaceAnimal) iterator.next();
2196            assertEquals(name, a.getName());
2197
2198        }
2199        for(Iterator JavaDoc iterator = resultR.iterator(); iterator.hasNext();)
2200        {
2201            Reptile a = (Reptile) iterator.next();
2202            assertEquals(name, a.getName());
2203        }
2204        for(Iterator JavaDoc iterator = resultM.iterator(); iterator.hasNext();)
2205        {
2206            Mammal a = (Mammal) iterator.next();
2207            assertEquals(name, a.getName());
2208        }
2209
2210        Reptile reptile = (Reptile) broker.getObjectByQuery(queryReptile);
2211        Mammal mammal = (Mammal) broker.getObjectByQuery(queryMammal);
2212        assertNotNull(reptile);
2213        assertNotNull(mammal);
2214    }
2215
2216}
2217
Popular Tags