-
Notifications
You must be signed in to change notification settings - Fork 161
/
StoredProcedureQueryTest.java
1290 lines (1063 loc) · 60.3 KB
/
StoredProcedureQueryTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2013, 2024 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0,
* or the Eclipse Distribution License v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
// Contributors:
// 01/23/2013-2.5 Guy Pelletier
// - 350487: JPA 2.1 Specification defined support for Stored Procedure Calls
package org.eclipse.persistence.testing.tests.advanced2;
import jakarta.persistence.EntityManager;
import jakarta.persistence.Parameter;
import jakarta.persistence.ParameterMode;
import jakarta.persistence.StoredProcedureQuery;
import jakarta.persistence.TransactionRequiredException;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.persistence.config.PersistenceUnitProperties;
import org.eclipse.persistence.queries.ColumnResult;
import org.eclipse.persistence.queries.ConstructorResult;
import org.eclipse.persistence.queries.EntityResult;
import org.eclipse.persistence.queries.FieldResult;
import org.eclipse.persistence.queries.ResultSetMappingQuery;
import org.eclipse.persistence.queries.SQLResultSetMapping;
import org.eclipse.persistence.queries.StoredProcedureCall;
import org.eclipse.persistence.sessions.server.ServerSession;
import org.eclipse.persistence.testing.framework.QuerySQLTracker;
import org.eclipse.persistence.testing.framework.jpa.junit.JUnitTestCase;
import org.eclipse.persistence.testing.models.jpa21.advanced.Address;
import org.eclipse.persistence.testing.models.jpa21.advanced.AdvancedTableCreator;
import org.eclipse.persistence.testing.models.jpa21.advanced.Employee;
import org.eclipse.persistence.testing.models.jpa21.advanced.EmployeeDetails;
import org.eclipse.persistence.testing.models.jpa21.advanced.LargeProject;
import org.eclipse.persistence.testing.models.jpa21.advanced.Project;
import org.eclipse.persistence.testing.models.jpa21.advanced.SmallProject;
import org.junit.Assert;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class StoredProcedureQueryTest extends JUnitTestCase {
public StoredProcedureQueryTest() {}
public StoredProcedureQueryTest(String name) {
super(name);
setPuName(getPersistenceUnitName());
}
@Override
public String getPersistenceUnitName() {
return "advanced2x";
}
public static Test suite() {
TestSuite suite = new TestSuite();
suite.setName("StoredProcedureQueryTest");
suite.addTest(new StoredProcedureQueryTest("testSetup"));
// Add the EM level stored procedure query tests.
suite.addTest(new StoredProcedureQueryTest("testQueryExecute1"));
suite.addTest(new StoredProcedureQueryTest("testQueryExecute2"));
suite.addTest(new StoredProcedureQueryTest("testQueryExecuteUpdate"));
suite.addTest(new StoredProcedureQueryTest("testQueryGetResultList"));
suite.addTest(new StoredProcedureQueryTest("testQueryWithMultipleResultsFromCode"));
suite.addTest(new StoredProcedureQueryTest("testQueryWithNamedFieldResult"));
suite.addTest(new StoredProcedureQueryTest("testQueryWithNamedFieldResultGetSingleResultOrNullWithValue"));
suite.addTest(new StoredProcedureQueryTest("testQueryWithNamedFieldResultGetSingleResultOrNullWithNull"));
suite.addTest(new StoredProcedureQueryTest("testQueryWithNamedFieldResultTranslationIntoNumbered"));
suite.addTest(new StoredProcedureQueryTest("testQueryWithNumberedFieldResult"));
suite.addTest(new StoredProcedureQueryTest("testQueryWithResultClass"));
suite.addTest(new StoredProcedureQueryTest("testQueryWithOutParam"));
suite.addTest(new StoredProcedureQueryTest("testStoredProcedureParameterAPI"));
suite.addTest(new StoredProcedureQueryTest("testStoredProcedureQuerySysCursor_Named"));
suite.addTest(new StoredProcedureQueryTest("testStoredProcedureQuerySysCursor_Positional"));
suite.addTest(new StoredProcedureQueryTest("testStoredProcedureQuerySysCursor_ResultList_Named"));
suite.addTest(new StoredProcedureQueryTest("testStoredProcedureQuerySysCursor_ResultList_Positional"));
suite.addTest(new StoredProcedureQueryTest("testStoredProcedureQueryExceptionWrapping1"));
suite.addTest(new StoredProcedureQueryTest("testStoredProcedureQueryExceptionWrapping2"));
// Add the named Annotation query tests.
suite.addTest(NamedStoredProcedureQueryTest.suite());
// These are EM API validation tests. These tests delete and update so
// be careful where you introduce new tests.
suite.addTest(new StoredProcedureQueryTest("testClassCastExceptionOnExecuteWithNoOutputParameters"));
suite.addTest(new StoredProcedureQueryTest("testGetResultListOnDeleteQuery"));
suite.addTest(new StoredProcedureQueryTest("testGetResultListOnUpdateQuery"));
suite.addTest(new StoredProcedureQueryTest("testGetSingleResultOnDeleteQuery"));
suite.addTest(new StoredProcedureQueryTest("testGetSingleResultOnUpdateQuery"));
return suite;
}
/**
* The setup is done as a test, both to record its failure, and to allow execution in the server.
*/
public void testSetup() {
new AdvancedTableCreator().replaceTables(getPersistenceUnitServerSession());
EmployeePopulator employeePopulator = new EmployeePopulator();
employeePopulator.buildExamples();
employeePopulator.persistExample(getPersistenceUnitServerSession());
clearCache();
}
/**
* Test a class cast exception.
*/
public void testClassCastExceptionOnExecuteWithNoOutputParameters() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
StoredProcedureQuery query = em.createStoredProcedureQuery("Read_All_Employees");
boolean returnValue = query.execute();
assertTrue("Execute didn't return true", returnValue);
@SuppressWarnings({"unchecked"})
List<Employee> employees = query.getResultList();
assertFalse("No employees were returned", employees.isEmpty());
} catch (ClassCastException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
fail("ClassCastException caught" + e);
} finally {
closeEntityManager(em);
}
}
}
/**
* Test an expected exception.
*/
public void testGetResultListOnDeleteQuery() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
boolean exceptionCaught = false;
try {
Object result = em.createStoredProcedureQuery("Delete_All_Responsibilities").getResultList();
} catch (IllegalStateException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
exceptionCaught = true;
} finally {
closeEntityManager(em);
}
assertTrue("Expected Illegal state exception was not caught", exceptionCaught);
}
}
/**
* Test an expected exception.
*/
public void testGetResultListOnUpdateQuery() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
boolean exceptionCaught = false;
try {
String postalCodeTypo = "R3 1B9";
String postalCodeCorrection = "R3B 1B9";
StoredProcedureQuery query = em.createStoredProcedureQuery("Update_Address_Postal_Code");
query.registerStoredProcedureParameter("new_p_code_v", String.class, ParameterMode.IN);
query.registerStoredProcedureParameter("old_p_code_v", String.class, ParameterMode.IN);
Object results = query.setParameter("new_p_code_v", postalCodeCorrection).setParameter("old_p_code_v", postalCodeTypo).getResultList();
} catch (IllegalStateException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
exceptionCaught = true;
} finally {
closeEntityManager(em);
}
assertTrue("Expected Illegal state exception was not caught", exceptionCaught);
}
}
/**
* Test an expected exception.
*/
public void testGetSingleResultOnDeleteQuery() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
boolean exceptionCaught = false;
try {
Object result = em.createStoredProcedureQuery("Delete_All_Responsibilities").getSingleResult();
} catch (IllegalStateException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
exceptionCaught = true;
} finally {
closeEntityManager(em);
}
assertTrue("Expected Illegal state exception was not caught", exceptionCaught);
}
}
/**
* Test an expected exception.
*/
public void testGetSingleResultOnUpdateQuery() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
boolean exceptionCaught = false;
try {
String postalCodeTypo = "R3 1B9";
String postalCodeCorrection = "R3B 1B9";
StoredProcedureQuery query = em.createStoredProcedureQuery("Update_Address_Postal_Code");
query.registerStoredProcedureParameter("new_p_code_v", String.class, ParameterMode.IN);
query.registerStoredProcedureParameter("old_p_code_v", String.class, ParameterMode.IN);
query.setParameter("new_p_code_v", postalCodeCorrection);
query.setParameter("old_p_code_v", postalCodeTypo);
// Make these calls to test the getParameter call with a name.
Parameter<?> paramNew = query.getParameter("new_p_code_v");
Parameter<?> paramOld = query.getParameter("old_p_code_v");
Object results = query.getSingleResult();
} catch (IllegalStateException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
exceptionCaught = true;
} finally {
closeEntityManager(em);
}
assertTrue("Expected Illegal state exception was not caught", exceptionCaught);
}
}
/**
* Tests a StoredProcedureQuery that does an update though EM API
*/
public void testQueryExecute1() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
// Create some data (with errors)
String postalCodeTypo = "K2J 0L8";
String postalCodeCorrection = "K2G 6W2";
beginTransaction(em);
Address address1 = new Address();
address1.setCity("Winnipeg");
address1.setPostalCode(postalCodeTypo);
address1.setProvince("MB");
address1.setStreet("510 Main Street");
address1.setCountry("Canada");
em.persist(address1);
Address address2 = new Address();
address2.setCity("Winnipeg");
address2.setPostalCode(postalCodeTypo);
address2.setProvince("MB");
address2.setStreet("512 Main Street");
address2.setCountry("Canada");
em.persist(address2);
Address address3 = new Address();
address3.setCity("Winnipeg");
address3.setPostalCode(postalCodeCorrection);
address3.setProvince("MB");
address3.setStreet("514 Main Street");
address3.setCountry("Canada");
em.persist(address3);
commitTransaction(em);
// Clear the cache
em.clear();
clearCache();
// Build the named stored procedure query, execute and test.
StoredProcedureQuery query = em.createStoredProcedureQuery("Result_Set_And_Update_Address", Address.class, Employee.class);
assertEquals("Parameter list was not empty.", 0, query.getParameters().size());
query.registerStoredProcedureParameter("new_p_code_v", String.class, ParameterMode.IN);
query.registerStoredProcedureParameter("old_p_code_v", String.class, ParameterMode.IN);
query.registerStoredProcedureParameter("employee_count_v", Integer.class, ParameterMode.OUT);
query.setParameter("new_p_code_v", postalCodeCorrection);
query.setParameter("old_p_code_v", postalCodeTypo);
boolean result = query.execute();
assertEquals("Parameter list size was incorrect, actual: " + query.getParameters().size() + ", expecting 3.", 3, query.getParameters().size());
Object parameterValue = query.getParameterValue("new_p_code_v");
assertEquals("The IN parameter value was not preserved, expected: " + postalCodeCorrection + ", actual: " + parameterValue, parameterValue, postalCodeCorrection);
assertTrue("Result did not return true for a result set.", result);
@SuppressWarnings({"unchecked"})
List<Address> addressResults = query.getResultList();
assertTrue("The query didn't have any more results.", query.hasMoreResults());
@SuppressWarnings({"unchecked"})
List<Employee> employeeResults = query.getResultList();
int numberOfEmployes = employeeResults.size();
// Should return false (no more results)
assertFalse("The query had more results.", query.hasMoreResults());
// Get the update count.
int updateCount = query.getUpdateCount();
assertEquals("Update count incorrect: " + updateCount, 2, updateCount);
// Update count should return -1 now.
assertEquals("Update count should be -1.", -1, query.getUpdateCount());
// Check output parameters by name.
Object outputParamValueFromName = query.getOutputParameterValue("employee_count_v");
assertNotNull("The output parameter was null.", outputParamValueFromName);
// TODO: to investigate. This little bit is hacky. For some
// reason MySql returns a Long here. By position is ok, that is,
// it returns an Integer (as we registered)
if (outputParamValueFromName instanceof Long) {
assertEquals("Incorrect value returned, expected " + numberOfEmployes + ", got: " + outputParamValueFromName, outputParamValueFromName, (long) numberOfEmployes);
} else if (outputParamValueFromName instanceof Integer) {
assertEquals("Incorrect value returned, expected " + numberOfEmployes + ", got: " + outputParamValueFromName, outputParamValueFromName, numberOfEmployes);
}
// TODO: else, don't worry about it for now ...
// Do some negative tests ...
try {
query.getOutputParameterValue(null);
fail("No IllegalArgumentException was caught with a null parameter name.");
} catch (IllegalArgumentException e) {
// Expected, swallow.
}
try {
query.getOutputParameterValue("emp_count");
fail("No IllegalArgumentException was caught with invalid parameter name.");
} catch (IllegalArgumentException e) {
// Expected, swallow.
}
try {
query.getOutputParameterValue("new_p_code_v");
fail("No IllegalArgumentException was caught with IN parameter name.");
} catch (IllegalArgumentException e) {
// Expected, swallow.
}
// Check output parameters by position.
Object outputParamValueFromPosition = query.getOutputParameterValue(3);
// TODO: See previous investigate todo. A Long is returned here instead of an Integer on MySQL.
// This test also mixes index and named parameters, so this test my be invalid to begin with.
assertNotNull("The output parameter was null.", outputParamValueFromPosition);
if (outputParamValueFromName instanceof Long) {
assertEquals("Incorrect value returned, expected " + numberOfEmployes + ", got: " + outputParamValueFromPosition, outputParamValueFromPosition, (long) numberOfEmployes);
} else if (outputParamValueFromName instanceof Integer) {
assertEquals("Incorrect value returned, expected " + numberOfEmployes + ", got: " + outputParamValueFromPosition, outputParamValueFromPosition, numberOfEmployes);
}
// Do some negative tests ...
try {
query.getOutputParameterValue(8);
fail("No IllegalArgumentException was caught with position out of bounds.");
} catch (IllegalArgumentException e) {
// Expected, swallow.
}
try {
query.getOutputParameterValue(1);
fail("No IllegalArgumentException was caught with an IN parameter position.");
} catch (IllegalArgumentException e) {
// Expected, swallow.
}
// Just because we don't trust anyone ... :-)
Address a1 = em.find(Address.class, address1.getId());
assertEquals("The postal code was not updated for address 1.", a1.getPostalCode(), postalCodeCorrection);
Address a2 = em.find(Address.class, address2.getId());
assertEquals("The postal code was not updated for address 2.", a2.getPostalCode(), postalCodeCorrection);
Address a3 = em.find(Address.class, address3.getId());
assertEquals("The postal code was not updated for address 3.", a3.getPostalCode(), postalCodeCorrection);
} finally {
// The open statement/connection will be closed here.
closeEntityManagerAndTransaction(em);
}
}
}
/**
* Tests a StoredProcedureQuery that does an update though EM API
* This is the same test as above except different retrieval path.
*/
public void testQueryExecute2() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
// Create some data (with errors)
String postalCodeTypo = "K2J 0L8";
String postalCodeCorrection = "K2G 6W2";
beginTransaction(em);
Address address1 = new Address();
address1.setCity("Winnipeg");
address1.setPostalCode(postalCodeTypo);
address1.setProvince("MB");
address1.setStreet("510 Main Street");
address1.setCountry("Canada");
em.persist(address1);
Address address2 = new Address();
address2.setCity("Winnipeg");
address2.setPostalCode(postalCodeTypo);
address2.setProvince("MB");
address2.setStreet("512 Main Street");
address2.setCountry("Canada");
em.persist(address2);
Address address3 = new Address();
address3.setCity("Winnipeg");
address3.setPostalCode(postalCodeCorrection);
address3.setProvince("MB");
address3.setStreet("514 Main Street");
address3.setCountry("Canada");
em.persist(address3);
commitTransaction(em);
// Clear the cache
em.clear();
clearCache();
// Build the named stored procedure query, execute and test.
StoredProcedureQuery query = em.createStoredProcedureQuery("Result_Set_And_Update_Address", Address.class, Employee.class);
query.registerStoredProcedureParameter("new_p_code_v", String.class, ParameterMode.IN);
query.registerStoredProcedureParameter("old_p_code_v", String.class, ParameterMode.IN);
query.registerStoredProcedureParameter("employee_count_v", Integer.class, ParameterMode.OUT);
boolean result = query.setParameter("new_p_code_v", postalCodeCorrection).setParameter("old_p_code_v", postalCodeTypo).execute();
assertTrue("Result did not return true for a result set.", result);
// This shouldn't affect where we are in the retrieval of the query.
assertTrue("We have didn't have any more results", query.hasMoreResults());
assertTrue("We have didn't have any more results", query.hasMoreResults());
assertTrue("We have didn't have any more results", query.hasMoreResults());
assertTrue("We have didn't have any more results", query.hasMoreResults());
assertTrue("We have didn't have any more results", query.hasMoreResults());
assertTrue("We have didn't have any more results", query.hasMoreResults());
assertTrue("We have didn't have any more results", query.hasMoreResults());
@SuppressWarnings({"unchecked"})
List<Address> addressResults = query.getResultList();
// We know there should be more results so ask for them without checking for has more results.
@SuppressWarnings({"unchecked"})
List<Employee> employeeResults = query.getResultList();
int numberOfEmployes = employeeResults.size();
// Should return false (no more results)
assertFalse("The query had more results.", query.hasMoreResults());
assertFalse("The query had more results.", query.hasMoreResults());
assertFalse("The query had more results.", query.hasMoreResults());
assertFalse("The query had more results.", query.hasMoreResults());
assertNull("getResultList after no results did not return null", query.getResultList());
// Get the update count.
int updateCount = query.getUpdateCount();
assertEquals("Update count incorrect: " + updateCount, 2, updateCount);
// Update count should return -1 now.
assertEquals("Update count should be -1.", -1, query.getUpdateCount());
assertEquals("Update count should be -1.", -1, query.getUpdateCount());
assertEquals("Update count should be -1.", -1, query.getUpdateCount());
assertEquals("Update count should be -1.", -1, query.getUpdateCount());
assertEquals("Update count should be -1.", -1, query.getUpdateCount());
// Check output parameters by name.
Object outputParamValueFromName = query.getOutputParameterValue("employee_count_v");
assertNotNull("The output parameter was null.", outputParamValueFromName);
// TODO: to investigate. This little bit is hacky. For some
// reason MySql returns a Long here. By position is ok, that is,
// it returns an Integer (as we registered)
if (outputParamValueFromName instanceof Long) {
assertEquals("Incorrect value returned, expected " + numberOfEmployes + ", got: " + outputParamValueFromName, outputParamValueFromName, (long) numberOfEmployes);
} else if (outputParamValueFromName instanceof Integer) {
assertEquals("Incorrect value returned, expected " + numberOfEmployes + ", got: " + outputParamValueFromName, outputParamValueFromName, numberOfEmployes);
}
// TODO: else, don't worry about it for now ...
// Do some negative tests ...
try {
query.getOutputParameterValue(null);
fail("No IllegalArgumentException was caught with a null parameter name.");
} catch (IllegalArgumentException e) {
// Expected, swallow.
}
try {
query.getOutputParameterValue("emp_count");
fail("No IllegalArgumentException was caught with invalid parameter name.");
} catch (IllegalArgumentException e) {
// Expected, swallow.
}
try {
query.getOutputParameterValue("new_p_code_v");
fail("No IllegalArgumentException was caught with IN parameter name.");
} catch (IllegalArgumentException e) {
// Expected, swallow.
}
// Check output parameters by position.
Object outputParamValueFromPosition = query.getOutputParameterValue(3);
// TODO: See previous investigate todo. A Long is returned here instead of an Integer on MySQL.
// This test also mixes index and named parameters, so this test my be invalid to begin with.
assertNotNull("The output parameter was null.", outputParamValueFromPosition);
if (outputParamValueFromName instanceof Long) {
assertEquals("Incorrect value returned, expected " + numberOfEmployes + ", got: " + outputParamValueFromPosition, outputParamValueFromPosition, (long) numberOfEmployes);
} else if (outputParamValueFromName instanceof Integer) {
assertEquals("Incorrect value returned, expected " + numberOfEmployes + ", got: " + outputParamValueFromPosition, outputParamValueFromPosition, numberOfEmployes);
}
// Do some negative tests ...
try {
query.getOutputParameterValue(8);
fail("No IllegalArgumentException was caught with position out of bounds.");
} catch (IllegalArgumentException e) {
// Expected, swallow.
}
try {
query.getOutputParameterValue(1);
fail("No IllegalArgumentException was caught with an IN parameter position.");
} catch (IllegalArgumentException e) {
// Expected, swallow.
}
// Just because we don't trust anyone ... :-)
Address a1 = em.find(Address.class, address1.getId());
assertEquals("The postal code was not updated for address 1.", a1.getPostalCode(), postalCodeCorrection);
Address a2 = em.find(Address.class, address2.getId());
assertEquals("The postal code was not updated for address 2.", a2.getPostalCode(), postalCodeCorrection);
Address a3 = em.find(Address.class, address3.getId());
assertEquals("The postal code was not updated for address 3.", a3.getPostalCode(), postalCodeCorrection);
} finally {
// The open statement/connection will be closed here.
closeEntityManagerAndTransaction(em);
}
}
}
/**
* Tests a StoredProcedureQuery that does an update though EM API
*/
public void testQueryExecuteUpdate() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
String postalCodeTypo = "R3 1B9";
String postalCodeCorrection = "R3B 1B9";
StoredProcedureQuery query = em.createStoredProcedureQuery("Update_Address_Postal_Code");
query.registerStoredProcedureParameter("new_p_code_v", String.class, ParameterMode.IN);
query.registerStoredProcedureParameter("old_p_code_v", String.class, ParameterMode.IN);
try {
query.setParameter("new_p_code_v", postalCodeCorrection).setParameter("old_p_code_v", postalCodeTypo).executeUpdate();
fail("TransactionRequiredException not caught");
} catch (TransactionRequiredException e) {
// ignore since expected exception.
}
beginTransaction(em);
Address address1 = new Address();
address1.setCity("Winnipeg");
address1.setPostalCode(postalCodeTypo);
address1.setProvince("MB");
address1.setStreet("510 Main Street");
address1.setCountry("Canada");
em.persist(address1);
Address address2 = new Address();
address2.setCity("Winnipeg");
address2.setPostalCode(postalCodeTypo);
address2.setProvince("MB");
address2.setStreet("512 Main Street");
address2.setCountry("Canada");
em.persist(address2);
em.flush();
// Clear the cache
em.clear();
clearCache();
query = em.createStoredProcedureQuery("Update_Address_Postal_Code");
query.registerStoredProcedureParameter("new_p_code_v", String.class, ParameterMode.IN);
query.registerStoredProcedureParameter("old_p_code_v", String.class, ParameterMode.IN);
int results = query.setParameter("new_p_code_v", postalCodeCorrection).setParameter("old_p_code_v", postalCodeTypo).executeUpdate();
assertEquals("Update count incorrect.", 2, results);
// Just because we don't trust anyone ... :-)
Address a1 = em.find(Address.class, address1.getId());
assertEquals("The postal code was not updated for address 1.", a1.getPostalCode(), postalCodeCorrection);
Address a2 = em.find(Address.class, address2.getId());
assertEquals("The postal code was not updated for address 2.", a2.getPostalCode(), postalCodeCorrection);
} finally {
closeEntityManagerAndTransaction(em);
}
}
}
/**
* Tests a StoredProcedureQuery that does an select though EM API
*/
public void testQueryGetResultList() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
beginTransaction(em);
Address address1 = new Address();
address1.setCity("Edmonton");
address1.setPostalCode("T5B 4M9");
address1.setProvince("AB");
address1.setStreet("7424 118 Avenue");
address1.setCountry("Canada");
em.persist(address1);
em.flush();
// Clear the cache
em.clear();
clearCache();
StoredProcedureQuery query = em.createStoredProcedureQuery("Read_Address");
query.registerStoredProcedureParameter("address_id_v", Integer.class, ParameterMode.IN);
@SuppressWarnings({"unchecked"})
List<Object[]> addresses = query.setParameter("address_id_v", address1.getId()).getResultList();
assertEquals("Incorrect number of addresses returned", 1, addresses.size());
Object[] addressContent = addresses.get(0);
assertEquals("Incorrect data content size", 6, addressContent.length);
assertEquals("Id content incorrect", addressContent[0], (long) address1.getId());
assertEquals("Steet content incorrect", addressContent[1], address1.getStreet());
assertEquals("City content incorrect", addressContent[2], address1.getCity());
assertEquals("Country content incorrect", addressContent[3], address1.getCountry());
assertEquals("Province content incorrect", addressContent[4], address1.getProvince());
assertEquals("Postal Code content incorrect", addressContent[5], address1.getPostalCode());
} finally {
closeEntityManagerAndTransaction(em);
}
}
}
/**
* Test multiple result sets by setting the SQL results set mapping from code.
*/
public void testQueryWithMultipleResultsFromCode() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
// SQL result set mapping for employee.
SQLResultSetMapping employeeResultSetMapping = new SQLResultSetMapping("EmployeeResultSetMapping");
employeeResultSetMapping.addResult(new EntityResult(Employee.class));
// SQL result set mapping for address.
SQLResultSetMapping addressResultSetMapping = new SQLResultSetMapping("AddressResultSetMapping");
addressResultSetMapping.addResult(new EntityResult(Address.class));
// SQL result set mapping for project (using inheritance and more complex result)
SQLResultSetMapping projectResultSetMapping = new SQLResultSetMapping("ProjectResultSetMapping");
EntityResult projectEntityResult = new EntityResult(Project.class);
projectResultSetMapping.addResult(projectEntityResult);
projectEntityResult = new EntityResult(SmallProject.class);
projectEntityResult.addFieldResult(new FieldResult("id", "SMALL_ID"));
projectEntityResult.addFieldResult(new FieldResult("name", "SMALL_NAME"));
projectEntityResult.addFieldResult(new FieldResult("description", "SMALL_DESCRIPTION"));
projectEntityResult.addFieldResult(new FieldResult("teamLeader", "SMALL_TEAMLEAD"));
projectEntityResult.addFieldResult(new FieldResult("version", "SMALL_VERSION"));
projectEntityResult.setDiscriminatorColumn("SMALL_DESCRIM");
projectResultSetMapping.addResult(projectEntityResult);
projectResultSetMapping.addResult(new ColumnResult("BUDGET_SUM"));
// SQL result set mapping for employee using constructor results.
SQLResultSetMapping employeeConstrustorResultSetMapping = new SQLResultSetMapping("EmployeeConstructorResultSetMapping");
ConstructorResult constructorResult = new ConstructorResult(EmployeeDetails.class);
ColumnResult columnResult = new ColumnResult("EMP_ID");
columnResult.getColumn().setType(Integer.class);
constructorResult.addColumnResult(columnResult);
columnResult = new ColumnResult("F_NAME");
columnResult.getColumn().setType(String.class);
constructorResult.addColumnResult(columnResult);
columnResult = new ColumnResult("L_NAME");
columnResult.getColumn().setType(String.class);
constructorResult.addColumnResult(columnResult);
columnResult = new ColumnResult("R_COUNT");
columnResult.getColumn().setType(Integer.class);
constructorResult.addColumnResult(columnResult);
employeeConstrustorResultSetMapping.addResult(constructorResult);
StoredProcedureCall call = new StoredProcedureCall();
call.setProcedureName("Read_Multiple_Result_Sets");
call.setHasMultipleResultSets(true);
call.setReturnMultipleResultSetCollections(true);
ResultSetMappingQuery query = new ResultSetMappingQuery(call);
query.addSQLResultSetMapping(employeeResultSetMapping);
query.addSQLResultSetMapping(addressResultSetMapping);
query.addSQLResultSetMapping(projectResultSetMapping);
query.addSQLResultSetMapping(employeeConstrustorResultSetMapping);
@SuppressWarnings({"unchecked"})
List<List<?>> allResults = (List<List<?>>) getPersistenceUnitServerSession().executeQuery(query);
assertNotNull("No results returned", allResults);
assertEquals("Incorrect number of results returned", 4, allResults.size());
// Verify first result set mapping --> Employee
List<?> results0 = allResults.get(0);
assertNotNull("No Employee results returned", results0);
assertTrue("Empty Employee results returned", !results0.isEmpty());
// Verify second result set mapping --> Address
List<?> results1 = allResults.get(1);
assertNotNull("No Address results returned", results1);
assertTrue("Empty Address results returned", !results1.isEmpty());
// Verify third result set mapping --> Project
List<?> results2 = allResults.get(2);
assertNotNull("No Project results returned", results2);
assertTrue("Empty Project results returned", !results2.isEmpty());
for (Object result2 : results2) {
Object[] result2Element = (Object[]) result2;
assertTrue("Failed to Return 3 items", (result2Element.length == 3));
// Using Number as Different db/drivers can return different types
// e.g. Oracle with ijdbc14.jar returns BigDecimal where as Derby
// with derbyclient.jar returns Double. NOTE: the order of checking
// here is valid and as defined by the spec.
assertTrue("Failed to return LargeProject", (result2Element[0] instanceof LargeProject));
assertTrue("Failed To Return SmallProject", (result2Element[1] instanceof SmallProject));
assertTrue("Failed to return column",(result2Element[2] instanceof Number));
Assert.assertNotEquals("Returned same data in both result elements", ((SmallProject) result2Element[1]).getName(), ((LargeProject) result2Element[0]).getName());
}
// Verify fourth result set mapping --> Employee Constructor Result
List<?> results3 = allResults.get(3);
assertNotNull("No Employee constructor results returned", results3);
assertTrue("Empty Employee constructor results returned", !results3.isEmpty());
}
}
/**
* Tests a StoredProcedureQuery using a result-set mapping though EM API
*/
public void testQueryWithNamedFieldResult() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
beginTransaction(em);
Address address = new Address();
address.setCity("Winnipeg");
address.setPostalCode("R3B 1B9");
address.setProvince("MB");
address.setStreet("510 Main Street");
address.setCountry("Canada");
em.persist(address);
em.flush();
// Clear the cache
em.clear();
clearCache();
StoredProcedureQuery query = em.createStoredProcedureQuery("Read_Address_Mapped_Named", "address-column-result-map");
query.registerStoredProcedureParameter("address_id_v", Integer.class, ParameterMode.IN);
Object[] values = (Object[]) query.setParameter("address_id_v", address.getId()).getSingleResult();
assertTrue("Address data not found or returned using stored procedure", ((values != null) && (values.length == 6)));
assertNotNull("No results returned from store procedure call", values[1]);
assertEquals("Address not found using stored procedure", address.getStreet(), values[1]);
} finally {
closeEntityManagerAndTransaction(em);
}
}
}
/**
* Tests a StoredProcedureQuery using a result-set mapping though EM API with getSingleResultOrNull() with some value as a result
*/
public void testQueryWithNamedFieldResultGetSingleResultOrNullWithValue() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
beginTransaction(em);
Address address = new Address();
address.setCity("Winnipeg");
address.setPostalCode("R3B 1B9");
address.setProvince("MB");
address.setStreet("510 Main Street");
address.setCountry("Canada");
em.persist(address);
em.flush();
// Clear the cache
em.clear();
clearCache();
StoredProcedureQuery query = em.createStoredProcedureQuery("Read_Address_Mapped_Named", "address-column-result-map");
query.registerStoredProcedureParameter("address_id_v", Integer.class, ParameterMode.IN);
Object[] values = (Object[]) query.setParameter("address_id_v", address.getId()).getSingleResultOrNull();
assertTrue("Address data not found or returned using stored procedure", ((values != null) && (values.length == 6)));
assertNotNull("No results returned from store procedure call", values[1]);
assertEquals("Address not found using stored procedure", address.getStreet(), values[1]);
} finally {
closeEntityManagerAndTransaction(em);
}
}
}
/**
* Tests a StoredProcedureQuery using a result-set mapping though EM API with getSingleResultOrNull() with null as a result
*/
public void testQueryWithNamedFieldResultGetSingleResultOrNullWithNull() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
beginTransaction(em);
Address address = new Address();
address.setCity("Winnipeg");
address.setPostalCode("R3B 1B9");
address.setProvince("MB");
address.setStreet("510 Main Street");
address.setCountry("Canada");
em.persist(address);
em.flush();
// Clear the cache
em.clear();
clearCache();
StoredProcedureQuery query = em.createStoredProcedureQuery("Read_Address_Mapped_Named", "address-column-result-map");
query.registerStoredProcedureParameter("address_id_v", Integer.class, ParameterMode.IN);
Object result = query.setParameter("address_id_v", 0).getSingleResultOrNull();
assertNull("Null is expected as a result", result);
} finally {
closeEntityManagerAndTransaction(em);
}
}
}
/**
* Tests a StoredProcedureQuery using a result-set mapping though EM API
*/
public void testQueryWithNamedFieldResultTranslationIntoNumbered() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
Map<String, String> properties = new HashMap<>();
properties.put(PersistenceUnitProperties.NAMING_INTO_INDEXED, "true");
EntityManager em = createEntityManager(properties);
QuerySQLTracker querySQLTracker = new QuerySQLTracker(em.unwrap(ServerSession.class));
try {
beginTransaction(em);
Address address = new Address();
address.setCity("Winnipeg");
address.setPostalCode("R3B 1B9");
address.setProvince("MB");
address.setStreet("510 Main Street");
address.setCountry("Canada");
em.persist(address);
em.flush();
// Clear the cache
em.clear();
clearCache();
StoredProcedureQuery query = em.createStoredProcedureQuery("Read_Address_Mapped_Named", "address-column-result-map");
query.registerStoredProcedureParameter("address_id_v", Integer.class, ParameterMode.IN);
Object[] values = (Object[]) query.setParameter("address_id_v", address.getId()).getSingleResult();
assertTrue("Address data not found or returned using stored procedure", ((values != null) && (values.length == 6)));
assertNotNull("No results returned from store procedure call", values[1]);
assertEquals("Address not found using stored procedure", address.getStreet(), values[1]);
String sqlStatement = querySQLTracker.getSqlStatements().get(0);
int count = (sqlStatement.split("=>", -1).length) - 1;
assertEquals("Transformation into numbered parameters was not called", 1, count);
} finally {
closeEntityManagerAndTransaction(em);
}
}
}
/**
* Tests a NamedStoredProcedureQuery using a result-set-mapping using
* positional parameters (and more than the procedure expects).
*/
public void testQueryWithNumberedFieldResult() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
beginTransaction(em);
Address address1 = new Address();
address1.setCity("Ottawa");
address1.setPostalCode("K2J 0L7");
address1.setProvince("ON");
address1.setStreet("321 Main");
address1.setCountry("Canada");
em.persist(address1);
em.flush();
// Clear the cache
em.clear();
clearCache();
StoredProcedureQuery query = em.createNamedStoredProcedureQuery("ReadAddressMappedNumberedFieldResult");
@SuppressWarnings({"unchecked"})
List<Address> addresses = query.setParameter(1, address1.getId()).getResultList();
assertEquals("Too many addresses returned", 1, addresses.size());
Address address2 = addresses.get(0);
assertNotNull("Address returned from stored procedure is null", address2);
assertTrue("Address didn't build correctly using stored procedure", (address1.getId() == address2.getId()));
assertEquals("Address didn't build correctly using stored procedure", address1.getStreet(), address2.getStreet());
assertEquals("Address didn't build correctly using stored procedure", address1.getCountry(), address2.getCountry());
assertEquals("Address didn't build correctly using stored procedure", address1.getProvince(), address2.getProvince());
assertEquals("Address didn't build correctly using stored procedure", address1.getPostalCode(), address2.getPostalCode());
} finally {
closeEntityManagerAndTransaction(em);
}
}
}
/**
* Tests a StoredProcedureQuery using a class though EM API
*/
public void testQueryWithResultClass() {
if (supportsStoredProcedures() && getPlatform().isMySQL()) {
EntityManager em = createEntityManager();
try {
beginTransaction(em);
Address address1 = new Address();
address1.setCity("Victoria");
address1.setPostalCode("V9A 6A9");
address1.setProvince("BC");
address1.setStreet("785 Lampson Street");
address1.setCountry("Canada");
em.persist(address1);
em.flush();