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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528
|
/*
* Copyright (c) 1998, 2019 Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1998, 2019 IBM Corporation. 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:
// Oracle - initial API and implementation from Oracle TopLink
// 05/5/2009-2.0 Guy Pelletier
// - 248489: JPA 2.0 Pessimistic Locking/Lock Mode support
// - Allows the configuration of pessimistic locking from JPA entity manager
// functions (find, refresh, lock) and from individual query execution.
// A pessimistic lock can be issued with a lock timeout value as well, in
// which case, for those databases that support LOCK WAIT will cause
// a LockTimeoutException to be thrown if the query fails as a result of
// a timeout trying to acquire the lock. A PessimisticLockException is
// thrown otherwise.
// 05/19/2010-2.1 ailitchev - Bug 244124 - Add Nested FetchGroup
// 09/21/2010-2.2 Frank Schwarz and ailitchev - Bug 325684 - QueryHints.BATCH combined with QueryHints.FETCH_GROUP_LOAD will cause NPE
// 3/13/2015 - Will Dazey
// - 458301 : Added check so that aggregate results won't attempt force version lock if locking type is set
package org.eclipse.persistence.queries;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import org.eclipse.persistence.annotations.BatchFetchType;
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.descriptors.FetchGroupManager;
import org.eclipse.persistence.descriptors.VersionLockingPolicy;
import org.eclipse.persistence.exceptions.DatabaseException;
import org.eclipse.persistence.exceptions.OptimisticLockException;
import org.eclipse.persistence.exceptions.QueryException;
import org.eclipse.persistence.expressions.Expression;
import org.eclipse.persistence.expressions.ExpressionBuilder;
import org.eclipse.persistence.history.AsOfClause;
import org.eclipse.persistence.internal.databaseaccess.DatabaseCall;
import org.eclipse.persistence.internal.descriptors.OptimisticLockingPolicy;
import org.eclipse.persistence.internal.expressions.FieldExpression;
import org.eclipse.persistence.internal.expressions.ForUpdateClause;
import org.eclipse.persistence.internal.expressions.ForUpdateOfClause;
import org.eclipse.persistence.internal.expressions.ObjectExpression;
import org.eclipse.persistence.internal.expressions.QueryKeyExpression;
import org.eclipse.persistence.internal.helper.DatabaseField;
import org.eclipse.persistence.internal.helper.DeferredLockManager;
import org.eclipse.persistence.internal.helper.InvalidObject;
import org.eclipse.persistence.internal.helper.NonSynchronizedVector;
import org.eclipse.persistence.internal.history.UniversalAsOfClause;
import org.eclipse.persistence.internal.queries.DatabaseQueryMechanism;
import org.eclipse.persistence.internal.queries.ExpressionQueryMechanism;
import org.eclipse.persistence.internal.queries.JoinedAttributeManager;
import org.eclipse.persistence.internal.queries.QueryByExampleMechanism;
import org.eclipse.persistence.internal.sessions.AbstractRecord;
import org.eclipse.persistence.internal.sessions.AbstractSession;
import org.eclipse.persistence.internal.sessions.UnitOfWorkImpl;
import org.eclipse.persistence.logging.SessionLog;
import org.eclipse.persistence.mappings.CollectionMapping;
import org.eclipse.persistence.mappings.DatabaseMapping;
import org.eclipse.persistence.mappings.ForeignReferenceMapping;
/**
* <p><b>Purpose</b>:
* Abstract class for all read queries using objects.
*
* <p><b>Description</b>:
* Contains common behavior for all read queries using objects.
*
* @author Yvon Lavoie
* @since TOPLink/Java 1.0
*/
public abstract class ObjectLevelReadQuery extends ObjectBuildingQuery {
/** Names of the possible lock mode types, JPA 1.0 and 2.0 */
public static final String READ = "READ";
public static final String WRITE = "WRITE";
/** Names of the possible lock mode types, JPA 2.0 only */
public static final String NONE = "NONE";
public static final String PESSIMISTIC_ = "PESSIMISTIC_";
public static final String PESSIMISTIC_READ = PESSIMISTIC_ + "READ";
public static final String PESSIMISTIC_WRITE = PESSIMISTIC_ + "WRITE";
public static final String PESSIMISTIC_FORCE_INCREMENT = PESSIMISTIC_ + "FORCE_INCREMENT";
public static final String OPTIMISTIC = "OPTIMISTIC";
public static final String OPTIMISTIC_FORCE_INCREMENT = "OPTIMISTIC_FORCE_INCREMENT";
/** Provide a default builder so that it's easier to be consistent */
protected ExpressionBuilder defaultBuilder;
/** Allow for the cache usage to be specified to enable in-memory querying. */
protected int cacheUsage;
// Note: UseDescriptorSetting will result in CheckCacheByPrimaryKey for most cases
// it simply allows the ClassDescriptor's disable cache hits to be used
public static final int UseDescriptorSetting = -1;
public static final int DoNotCheckCache = 0;
public static final int CheckCacheByExactPrimaryKey = 1;
public static final int CheckCacheByPrimaryKey = 2;
public static final int CheckCacheThenDatabase = 3;
public static final int CheckCacheOnly = 4;
public static final int ConformResultsInUnitOfWork = 5;
/**
* Allow for additional fields to be selected, used for m-m batch reading.
* Can contain DatabaseField or Expression.
*/
protected List<Object> additionalFields;
/** Allow for a complex result to be return including the rows and objects, used for m-m batch reading. */
protected boolean shouldIncludeData;
/** Allow a prePrepare stage to build the expression for EJBQL and QBE and resolve joining. */
protected boolean isPrePrepared;
/** Indicates if distinct should be used or not. */
protected short distinctState;
public static final short UNCOMPUTED_DISTINCT = 0;
public static final short USE_DISTINCT = 1;
public static final short DONT_USE_DISTINCT = 2;
/**
* Used to determine behavior of indirection in in-memory querying and conforming.
*/
protected int inMemoryQueryIndirectionPolicy;
/**
* {@link FetchGroup} specified on this query. When set this FetchGroup will
* override the {@link #fetchGroupName} and the use of the descriptor's
* {@link FetchGroupManager#getDefaultFetchGroup()}
*/
protected FetchGroup fetchGroup;
/**
* Name of {@link FetchGroup} stored in the {@link FetchGroupManager} of the
* reference class' descriptor or any of its parent descriptors.
*/
protected String fetchGroupName;
/** Flag to turn on/off the use of the default fetch group. */
protected boolean shouldUseDefaultFetchGroup = true;
/** Specifies indirection that should be instantiated before returning result */
protected LoadGroup loadGroup;
/**
* Stores the non fetchjoin attributes, these are joins that will be
* represented in the where clause but not in the select.
*/
protected List<Expression> nonFetchJoinAttributeExpressions;
/** Stores the partial attributes that have been added to this query */
protected List<Expression> partialAttributeExpressions;
/** Stores the helper object for dealing with joined attributes */
protected JoinedAttributeManager joinedAttributeManager;
/** Defines batch fetching configuration. */
protected BatchFetchPolicy batchFetchPolicy;
/** PERF: Caches locking policy isReferenceClassLocked setting. */
protected Boolean isReferenceClassLocked;
/** PERF: Allow queries to build directly from the database result-set. */
protected boolean isResultSetOptimizedQuery = false;
/** PERF: Allow queries to build while accessing the database result-set. Skips accessing result set non-pk fields in case the cached object is found.
If ResultSet optimization is used (isResultSetOptimizedQuery is set to true) then ResultSet Access optimization is ignored. */
protected Boolean isResultSetAccessOptimizedQuery;
/** If neither query specifies isResultSetOptimizedQuery nor session specifies shouldOptimizeResultSetAccess
* then this value is used to indicate whether optimization should be attempted
*/
public static boolean isResultSetAccessOptimizedQueryDefault = false;
/** PERF: Indicates whether the query is actually using ResultSet optimization. If isResultSetOptimizedQuery==null set automatically before executing call. */
protected transient Boolean usesResultSetAccessOptimization;
/** PERF: Allow queries to be defined as read-only in unit of work execution. */
protected boolean isReadOnly = false;
/** Define if an outer join should be used to read subclasses. */
protected Boolean shouldOuterJoinSubclasses;
/** Allow concrete subclasses calls to be prepared and cached for inheritance queries. */
protected Map<Class, DatabaseCall> concreteSubclassCalls;
/** Allow concrete subclasses queries to be prepared and cached for inheritance queries. */
protected Map<Class, DatabaseQuery> concreteSubclassQueries;
/** Allow aggregate queries to be prepared and cached. */
protected Map<DatabaseMapping, ObjectLevelReadQuery> aggregateQueries;
/** Allow concrete subclasses joined mapping indexes to be prepared and cached for inheritance queries. */
protected Map<Class, Map<DatabaseMapping, Object>> concreteSubclassJoinedMappingIndexes;
/** Used when specifying a lock mode for the query */
protected String lockModeType;
/**
* waitTimeout has three possible setting: null, 0 and 1..N
* null: use the session.getPessimisticLockTimeoutDefault() if available.
* 0: issue a LOCK_NOWAIT
* 1..N: use this value to set the WAIT clause.
*/
protected Integer waitTimeout;
//wait timeout unit
protected TimeUnit waitTimeoutUnit;
/** Used for ordering support. */
protected List<Expression> orderByExpressions;
/** Indicates whether pessimistic lock should also be applied to relation tables (ManyToMany and OneToOne mappings),
* reference tables (DirectCollection and AggregateCollection mapping).
*/
protected boolean shouldExtendPessimisticLockScope;
/**
* Allow a query's results to be unioned (UNION, INTERSECT, EXCEPT) with another query results.
*/
protected List<Expression> unionExpressions;
/** Indicates whether the query is cached as an expression query in descriptor's query manager. */
protected boolean isCachedExpressionQuery;
/** default value for shouldUseSerializedObjectPolicy */
public static boolean shouldUseSerializedObjectPolicyDefault = true;
/** Indicates whether the query should use SerializedObjectPolicy if descriptor has it.*/
protected boolean shouldUseSerializedObjectPolicy;
/**
* INTERNAL:
* Initialize the state of the query
*/
public ObjectLevelReadQuery() {
this.shouldRefreshIdentityMapResult = false;
this.distinctState = UNCOMPUTED_DISTINCT;
this.cacheUsage = UseDescriptorSetting;
this.shouldIncludeData = false;
this.inMemoryQueryIndirectionPolicy = InMemoryQueryIndirectionPolicy.SHOULD_THROW_INDIRECTION_EXCEPTION;
this.isCacheCheckComplete = false;
this.shouldUseSerializedObjectPolicy = shouldUseSerializedObjectPolicyDefault;
}
/**
* PUBLIC:
* Union the query results with the other query.
*/
public void union(ReportQuery query) {
addUnionExpression(getExpressionBuilder().union(query));
}
/**
* PUBLIC:
* Intersect the query results with the other query.
*/
public void intersect(ReportQuery query) {
addUnionExpression(getExpressionBuilder().intersect(query));
}
/**
* PUBLIC:
* Except the query results with the other query.
*/
public void except(ReportQuery query) {
addUnionExpression(getExpressionBuilder().except(query));
}
/**
* PUBLIC:
* Add the union expression to the query.
* A union expression must be created with the query's expression builder
* and one of union/unionAll/intersect/intersectAll/except/exceptAll with a subquery expression.
*/
public void addUnionExpression(Expression union) {
setIsPrepared(false);
getUnionExpressions().add(union);
}
/**
* Return any union expressions.
*/
public List<Expression> getUnionExpressions() {
if (unionExpressions == null) {
unionExpressions = new ArrayList<Expression>();
}
return unionExpressions;
}
/**
* INTERNAL:
* Set any union expressions.
*/
public void setUnionExpressions(List<Expression> unionExpressions) {
this.unionExpressions = unionExpressions;
}
/**
* PUBLIC:
* Order the query results by the object's attribute or query key name.
*/
public void addDescendingOrdering(String queryKeyName) {
addOrdering(getExpressionBuilder().get(queryKeyName).descending());
}
/**
* PUBLIC:
* Add the ordering expression. This allows for ordering across relationships or functions.
* Example: readAllQuery.addOrdering(expBuilder.get("address").get("city").toUpperCase().descending())
*/
public void addOrdering(Expression orderingExpression) {
getOrderByExpressions().add(orderingExpression);
//Bug2804042 Must un-prepare if prepared as the SQL may change.
setIsPrepared(false);
setShouldOuterJoinSubclasses(true);
}
/**
* INTERNAL:
* Return if the query is equal to the other.
* This is used to allow dynamic expression query SQL to be cached.
*/
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if ((object == null) || (!getClass().equals(object.getClass()))) {
return false;
}
ObjectLevelReadQuery query = (ObjectLevelReadQuery) object;
// Only check expression queries for now.
if ((!isExpressionQuery()) || (!isDefaultPropertiesQuery())) {
return this == object;
}
if (!getExpressionBuilder().equals(query.getExpressionBuilder())) {
return false;
}
if (this.distinctState != query.distinctState) {
return false;
}
if (hasJoining()) {
if (!query.hasJoining()) {
return false;
}
List joinedAttributes = getJoinedAttributeManager().getJoinedAttributeExpressions();
List otherJoinedAttributes = query.getJoinedAttributeManager().getJoinedAttributeExpressions();
int size = joinedAttributes.size();
if (size != otherJoinedAttributes.size()) {
return false;
}
for (int index = 0; index < size; index++) {
if (!joinedAttributes.get(index).equals(otherJoinedAttributes.get(index))) {
return false;
}
}
} else if (query.hasJoining()) {
return false;
}
if (hasOrderByExpressions()) {
if (!query.hasOrderByExpressions()) {
return false;
}
List orderBys = getOrderByExpressions();
List otherOrderBys = query.getOrderByExpressions();
int size = orderBys.size();
if (size != otherOrderBys.size()) {
return false;
}
for (int index = 0; index < size; index++) {
if (!orderBys.get(index).equals(otherOrderBys.get(index))) {
return false;
}
}
} else if (query.hasOrderByExpressions()) {
return false;
}
if (! ((this.referenceClass == query.referenceClass) || ((this.referenceClass != null) && this.referenceClass.equals(query.referenceClass)))) {
return false;
}
Expression selectionCriteria = getSelectionCriteria();
Expression otherSelectionCriteria = query.getSelectionCriteria();
return ((selectionCriteria == otherSelectionCriteria) || ((selectionCriteria != null) && selectionCriteria.equals(otherSelectionCriteria)));
}
/**
* INTERNAL:
* Compute a consistent hash-code for the expression.
* This is used to allow dynamic expression's SQL to be cached.
*/
@Override
public int hashCode() {
if (!isExpressionQuery()) {
return super.hashCode();
}
int hashCode = 32;
if (this.referenceClass != null) {
hashCode = hashCode + this.referenceClass.hashCode();
}
Expression selectionCriteria = getSelectionCriteria();
if (selectionCriteria != null) {
hashCode = hashCode + selectionCriteria.hashCode();
}
return hashCode;
}
/**
* PUBLIC:
* Return if the query is read-only.
* This allows queries executed against a UnitOfWork to be read-only.
* This means the query will be executed against the Session,
* and the resulting objects will not be tracked for changes.
* The resulting objects are from the Session shared cache,
* and must not be modified.
*/
public boolean isReadOnly() {
return isReadOnly;
}
/**
* PUBLIC:
* Set the query to be read-only.
* This allows queries executed against a UnitOfWork to be read-only.
* This means the query will be executed against the Session,
* and the resulting objects will not be tracked for changes.
* The resulting objects are from the Session shared cache,
* and must not be modified.
*/
public void setIsReadOnly(boolean isReadOnly) {
this.isReadOnly = isReadOnly;
}
/**
* PUBLIC:
* Sets that this a pessimistic wait locking query.
* <ul>
* <li>ObjectBuildingQuery.LOCK: SELECT .... FOR UPDATE WAIT issued.
* </ul>
* <p>Fine Grained Locking: On execution the reference class and those of
* all joined attributes will be checked. If any of these have a
* PessimisticLockingPolicy set on their descriptor, they will be locked
* in a SELECT ... FOR UPDATE OF ... {NO WAIT}. Issues fewer locks
* and avoids setting the lock mode on each query.
*
* <p>Example:
* <code>readAllQuery.setSelectionCriteria(employee.get("address").equal("Ottawa"));</code>
* <ul>
* <li>LOCK: all employees in Ottawa and all referenced Ottawa addresses
* will be locked and the lock will wait only the specified amount of time.
* </ul>
* @see org.eclipse.persistence.descriptors.PessimisticLockingPolicy
*/
public void setWaitTimeout(Integer waitTimeout) {
this.waitTimeout = waitTimeout;
setIsPrePrepared(false);
setIsPrepared(false);
setWasDefaultLockMode(false);
}
public void setWaitTimeoutUnit(TimeUnit waitTimeoutUnit) {
this.waitTimeoutUnit = waitTimeoutUnit;
}
/**
* INTERNAL:
* Check and return custom query flag. Custom query flag value is initialized when stored value is {@code null}.
* Called from {@link #checkForCustomQuery(AbstractSession, AbstractRecord)} to retrieve custom query flag.
* @param session Current session.
* @param translationRow Database record.
* @return Current custom query flag. Value shall never be {@code null}.
*/
protected abstract Boolean checkCustomQueryFlag(final AbstractSession session, final AbstractRecord translationRow);
/**
* INTERNAL:
* Get custom read query from query manager.
* Called from {@link #checkForCustomQuery(AbstractSession, AbstractRecord)} to retrieve custom read query.
* @return Custom read query from query manager.
*/
protected abstract ObjectLevelReadQuery getReadQuery();
/**
* INTERNAL:
* Check to see if a custom query should be used for this query.
* This is done before the query is copied and prepared/executed. Value of {@code null} means there is none.
* @param session Current session.
* @param translationRow Database record.
* @return Custom database query or {@code null} when custom database query is not set.
*/
@Override
protected DatabaseQuery checkForCustomQuery(final AbstractSession session, final AbstractRecord translationRow) {
final Boolean useCustomQuery = checkCustomQueryFlag(session, translationRow);
checkDescriptor(session);
ObjectLevelReadQuery customQuery;
if (useCustomQuery != null && useCustomQuery.booleanValue()) {
customQuery = getReadQuery();
if (this.accessors != null) {
customQuery = (ObjectLevelReadQuery) customQuery.clone();
customQuery.setIsExecutionClone(true);
customQuery.setAccessors(this.accessors);
}
} else {
customQuery = null;
}
isCustomQueryUsed = useCustomQuery;
return customQuery;
}
/**
* INTERNAL:
* Creates and returns a copy of this query.
* @return A clone of this instance.
*/
@Override
public Object clone() {
final ObjectLevelReadQuery cloneQuery = (ObjectLevelReadQuery)super.clone();
// Must also clone the joined expressions as always joined attribute will be added
// don't use setters as this will trigger unprepare.
if (joinedAttributeManager != null) {
cloneQuery.joinedAttributeManager = joinedAttributeManager.clone();
cloneQuery.joinedAttributeManager.setBaseQuery(cloneQuery);
}
if (this.batchFetchPolicy != null) {
cloneQuery.batchFetchPolicy = batchFetchPolicy.clone();
}
if (this.nonFetchJoinAttributeExpressions != null){
cloneQuery.nonFetchJoinAttributeExpressions = new ArrayList<>(nonFetchJoinAttributeExpressions);
}
// Don't use setters as that will trigger unprepare
if (this.orderByExpressions != null) {
cloneQuery.orderByExpressions = new ArrayList<>(this.orderByExpressions);
}
if (this.fetchGroup != null) {
cloneQuery.fetchGroup = fetchGroup.clone();
// don't clone immutable entityFetchGroup
}
return cloneQuery;
}
/**
* INTERNAL:
* Clone the query, including its selection criteria.
* <p>
* Normally selection criteria are not cloned here as they are cloned
* later on during prepare.
*/
@Override
public Object deepClone() {
ObjectLevelReadQuery clone = (ObjectLevelReadQuery)clone();
if (getSelectionCriteria() != null) {
clone.setSelectionCriteria((Expression)getSelectionCriteria().clone());
}
if (defaultBuilder != null) {
clone.defaultBuilder = (ExpressionBuilder)defaultBuilder.clone();
}
return clone;
}
/**
* PUBLIC:
* Set the query to lock, this will also turn refreshCache on.
*/
public void acquireLocks() {
setLockMode(LOCK);
//Bug2804042 Must un-prepare if prepared as the SQL may change.
setIsPrepared(false);
}
/**
* PUBLIC:
* Set the query to lock without waiting (blocking), this will also turn refreshCache on.
*/
public void acquireLocksWithoutWaiting() {
setLockMode(LOCK_NOWAIT);
//Bug2804042 Must un-prepare if prepared as the SQL may change.
setIsPrepared(false);
}
/**
* INTERNAL:
* Additional fields can be added to a query. This is used in m-m batch reading to bring back the key from the join table.
*/
public void addAdditionalField(DatabaseField field) {
getAdditionalFields().add(field);
// Bug2804042 Must un-prepare if prepared as the SQL may change.
setIsPrepared(false);
}
/**
* INTERNAL:
* Additional fields can be added to a query. This is used in m-m batch reading to bring back the key from the join table.
*/
public void addAdditionalField(Expression fieldExpression) {
getAdditionalFields().add(fieldExpression);
// Bug2804042 Must un-prepare if prepared as the SQL may change.
setIsPrepared(false);
}
/**
* PUBLIC:
* Specify the relationship attribute to be join fetched in this query.
* The query will join the object(s) being read with the attribute,
* this allows all of the data required for the object(s) to be read in a single query instead of (n) queries.
* This should be used when the application knows that it requires the part for all of the objects being read.
*
* <p>Note: This cannot be used for objects where it is possible not to have a part,
* as these objects will be omitted from the result set,
* unless an outer join is used through passing and expression using "getAllowingNull".
* To join fetch collection relationships use the addJoinedAttribute(Expression) using "anyOf" to "anyOfAllowingNone".
*
* <p>Example: query.addJoinedAttribute("address")
*
* @see #addJoinedAttribute(Expression)
* @see ReadAllQuery#addBatchReadAttribute(Expression)
*/
public void addJoinedAttribute(String attributeName) {
addJoinedAttribute(getExpressionBuilder().get(attributeName));
}
/**
* PUBLIC:
* Specify the attribute to be join fetched in this query.
* The query will join the object(s) being read with the specified attribute,
* this allows all of the data required for the object(s) to be read in a single query instead of (n) queries.
* This should be used when the application knows that it requires the part for all of the objects being read.
*
* <p>Note: This cannot be used for objects where it is possible not to have a part,
* as these objects will be omitted from the result set,
* unless an outer join is used through passing and expression using "getAllowingNull".
*
* <p>Example:
* The following will fetch along with Employee(s) "Jones" all projects they participate in
* along with teamLeaders and their addresses, teamMembers and their phones.
*
* query.setSelectionCriteria(query.getExpressionBuilder().get("lastName").equal("Jones"));
* Expression projects = query.getExpressionBuilder().anyOf("projects");
* query.addJoinedAttribute(projects);
* Expression teamLeader = projects.get("teamLeader");
* query.addJoinedAttribute(teamLeader);
* Expression teamLeaderAddress = teamLeader.getAllowingNull("address");
* query.addJoinedAttribute(teamLeaderAddress);
* Expression teamMembers = projects.anyOf("teamMembers");
* query.addJoinedAttribute(teamMembers);
* Expression teamMembersPhones = teamMembers.anyOfAllowingNone("phoneNumbers");
* query.addJoinedAttribute(teamMembersPhones);
*
* Note that:
* the order is essential: an expression should be added before any expression derived from it;
* the object is built once - it won't be rebuilt if it to be read again as a joined attribute:
* in the example the query won't get phones for "Jones" -
* even though they are among teamMembers (for whom phones are read).
*
*/
public void addJoinedAttribute(Expression attributeExpression) {
getJoinedAttributeManager().addJoinedAttributeExpression(attributeExpression);
// Bug2804042 Must un-prepare if prepared as the SQL may change.
// Joined attributes are now calculated in prePrepare.
setIsPrePrepared(false);
}
/**
* PUBLIC:
* Specify the relationship attribute to be join in this query.
* This allows the query results to be filtered based on the relationship join.
* The query will join the object(s) being read with the attribute.
* The difference between this and a joined fetched attribute is that
* it does not select the joined data nor populate the joined attribute,
* it is only used to filter the query results.
*
* <p>Example: query.addNonFetchJoinedAttribute("address")
*
* @see #addNonFetchJoinedAttribute(Expression)
*/
public void addNonFetchJoinedAttribute(String attributeName) {
addNonFetchJoin(getExpressionBuilder().get(attributeName));
}
/**
* PUBLIC:
* Specify the relationship attribute to be join in this query.
* This allows the query results to be filtered based on the relationship join.
* The query will join the object(s) being read with the attribute.
* The difference between this and a joined fetched attribute is that
* it does not select the joined data nor populate the joined attribute,
* it is only used to filter the query results.
*
* <p>Example: query.addNonFetchJoinedAttribute(query.getExpressionBuilder().get("teamLeader").get("address"))
*
* @see #addNonFetchJoinedAttribute(Expression)
*/
public void addNonFetchJoinedAttribute(Expression attributeExpression) {
addNonFetchJoin(attributeExpression);
}
/**
* PUBLIC:
* Specify the object expression to be joined in this query.
* This allows the query results to be filtered based on the join to the object.
* The object should define an on clause that defines the join condition.
* This allows for two non-related objects to be joined.
*
* <p>Example: (select all employees that are a team leader)</p>
* <pre>
* ExpressionBuilder project = new ExpressionBuilder(Project.class);
* ExpressionBuilder employee = new ExpressionBuilder(Employee.class);
* ReadAllQuery query = new ReadAllQuery(Employee.class, employee);
* query.addJoin(project.on(project.get("teamLeader").equal(employee)))
* </pre>
*/
public void addNonFetchJoin(Expression target) {
getNonFetchJoinAttributeExpressions().add(target);
if (target.isObjectExpression() && ((ObjectExpression)target).shouldUseOuterJoin()) {
this.setShouldBuildNullForNullPk(true);
}
// Bug 2804042 Must un-prepare if prepared as the SQL may change.
// Joined attributes are now calculated in prePrepare.
setIsPrePrepared(false);
}
/**
* PUBLIC:
* Specify that only a subset of the class' attributes be selected in this query.
* <p>
* This allows for the query to be optimized through selecting less data.
* <p>
* Partial objects will be returned from the query, where the unspecified attributes will be left <code>null</code>.
* The primary key will always be selected to allow re-querying of the whole object.
* <p>Note: Because the object is not fully initialized it cannot be cached, and cannot be edited.
* <p>Note: You cannot have 2 partial attributes of the same type. You also cannot
* add a partial attribute which is of the same type as the class being queried.
* <p><b>Example</b>: query.addPartialAttribute("firstName")
* @see #addPartialAttribute(Expression)
* @deprecated since EclipseLink 2.1, partial attributes replaced by fetch groups.
* @see FetchGroup
* Example:
* FetchGroup fetchGroup = new FetchGroup();
* fetchGroup.addAttribute("address.city");
* query.setFetchGroup(fetchGroup);
*/
public void addPartialAttribute(String attributeName) {
addPartialAttribute(getExpressionBuilder().get(attributeName));
}
/**
* INTERNAL:
* The method adds to the passed input vector the
* fields or expressions corresponding to the passed join expression.
*/
protected void addSelectionFieldsForJoinedExpression(List fields, boolean isCustomSQL, Expression expression) {
if(isCustomSQL) {
// Expression may not have been initialized.
ExpressionBuilder builder = expression.getBuilder();
builder.setSession(getSession().getRootSession(null));
builder.setQueryClass(getReferenceClass());
}
ForeignReferenceMapping mapping = (ForeignReferenceMapping)((QueryKeyExpression)expression).getMapping();
ClassDescriptor referenceDescriptor = mapping.getReferenceDescriptor();
// Add the fields defined by the nested fetch group - if it exists.
ObjectLevelReadQuery nestedQuery = null;
if (referenceDescriptor != null && referenceDescriptor.hasFetchGroupManager()) {
nestedQuery = getJoinedAttributeManager().getNestedJoinedMappingQuery(expression);
FetchGroup nestedFetchGroup = nestedQuery.getExecutionFetchGroup();
if(nestedFetchGroup != null) {
List<DatabaseField> nestedFields = nestedQuery.getFetchGroupSelectionFields(mapping);
for(DatabaseField field : nestedFields) {
fields.add(new FieldExpression(field, expression));
}
return;
}
}
if(isCustomSQL) {
if(referenceDescriptor != null) {
if (nestedQuery == null) {
nestedQuery = getJoinedAttributeManager().getNestedJoinedMappingQuery(expression);
}
fields.addAll(referenceDescriptor.getAllSelectionFields(nestedQuery));
} else {
fields.add(expression);
}
} else {
fields.add(expression);
}
}
/**
* ADVANCED: Sets the query to execute as of the past time.
* Both the query execution and result will conform to the database as it
* existed in the past.
* <p>
* Equivalent to query.getSelectionCriteria().asOf(pastTime) called
* immediately before query execution.
* <p>An as of clause at the query level will override any clauses set at the
* expression level. Useful in cases where the selection criteria is not known in
* advance, such as for query by example or primary key (selection object), or
* where you do not need to cache the result (report query).
* <p>Ideally an as of clause at the session level is superior as query
* results can then be cached. You must set
* {@link org.eclipse.persistence.queries.ObjectLevelReadQuery#setShouldMaintainCache setShouldMaintainCache(false)}
* <p>To query all joined/batched attributes as of the same time set
* this.{@link org.eclipse.persistence.queries.ObjectLevelReadQuery#cascadeAllParts cascadeAllParts()}.
* @throws QueryException (at execution time) unless
* <code>setShouldMaintainCache(false)</code> is set. If some more recent
* data were in the cache, this would be returned instead, and both the
* cache and query result would become inconsistent.
* @since OracleAS TopLink 10<i>g</i> (10.0.3)
* @see #hasAsOfClause
* @see org.eclipse.persistence.sessions.Session#acquireHistoricalSession(org.eclipse.persistence.history.AsOfClause)
* @see org.eclipse.persistence.expressions.Expression#asOf(org.eclipse.persistence.history.AsOfClause)
*/
public void setAsOfClause(AsOfClause pastTime) {
getExpressionBuilder().asOf(new UniversalAsOfClause(pastTime));
setIsPrepared(false);
}
/**
* PUBLIC:
* Specify that only a subset of the class' attributes be selected in this query.
* <p>This allows for the query to be optimized through selecting less data.
* <p>Partial objects will be returned from the query, where the unspecified attributes will be left <code>null</code>.
* The primary key will always be selected to allow re-querying of the whole object.
* <p>Note: Because the object is not fully initialized it cannot be cached, and cannot be edited.
* <p>Note: You cannot have 2 partial attributes of the same type. You also cannot
* add a partial attribute which is of the same type as the class being queried.
* <p><b>Example</b>: query.addPartialAttribute(query.getExpressionBuilder().get("address").get("city"))
* @deprecated since EclipseLink 2.1, partial attributes replaced by fetch groups.
* @see FetchGroup
* Example:
* FetchGroup fetchGroup = new FetchGroup();
* fetchGroup.addAttribute("address.city");
* query.setFetchGroup(fetchGroup);
*/
public void addPartialAttribute(Expression attributeExpression) {
getPartialAttributeExpressions().add(attributeExpression);
//Bug2804042 Must un-prepare if prepared as the SQL may change.
setIsPrepared(false);
}
/**
* INTERNAL:
* Used to build the object, and register it if in the context of a unit of work.
*/
@Override
public Object buildObject(AbstractRecord row) {
return this.descriptor.getObjectBuilder().buildObject(this, row, this.joinedAttributeManager);
}
/**
* PUBLIC:
* The cache will checked completely, if the object is not found null will be returned or an error if the query is too complex.
* Queries can be configured to use the cache at several levels.
* Other caching option are available.
* @see #setCacheUsage(int)
*/
public void checkCacheOnly() {
setCacheUsage(CheckCacheOnly);
}
/**
* INTERNAL:
* Ensure that the descriptor has been set.
* @param session Current session.
*/
@Override
public void checkDescriptor(AbstractSession session) throws QueryException {
if (this.descriptor == null) {
if (getReferenceClass() == null) {
throw QueryException.referenceClassMissing(this);
}
ClassDescriptor referenceDescriptor = session.getDescriptor(getReferenceClass());
if (referenceDescriptor == null) {
throw QueryException.descriptorIsMissing(getReferenceClass(), this);
}
setDescriptor(referenceDescriptor);
}
}
/**
* INTERNAL:
* Contains the body of the check early return call, implemented by subclasses.
*/
protected abstract Object checkEarlyReturnLocal(AbstractSession session, AbstractRecord translationRow);
/**
* INTERNAL:
* Check to see if this query already knows the return value without performing any further work.
*/
@Override
public Object checkEarlyReturn(AbstractSession session, AbstractRecord translationRow) {
// For bug 3136413/2610803 building the selection criteria from an EJBQL string or
// an example object is done just in time.
// Also calls checkDescriptor here.
//buildSelectionCriteria(session);
checkPrePrepare(session);
if (!session.isUnitOfWork()) {
return checkEarlyReturnLocal(session, translationRow);
}
UnitOfWorkImpl unitOfWork = (UnitOfWorkImpl)session;
// The cache check must happen on the UnitOfWork in these cases either
// to access transient state or for pessimistic locking, as only the
// UOW knows which objects it has locked.
Object result = null;
// PERF: Avoid uow check for read-only.
if (!this.descriptor.shouldBeReadOnly()) {
result = checkEarlyReturnLocal(unitOfWork, translationRow);
}
if (result != null) {
return result;
}
// PERF: If a locking query, or isolated always, then cache is ignored, so no point checking.
// An error should be thrown on prepare is checkCacheOnly is used with these.
if ((!unitOfWork.isNestedUnitOfWork()) && (this.descriptor.getCachePolicy().shouldIsolateObjectsInUnitOfWork() || isLockQuery()) || unitOfWork.shouldForceReadFromDB(this, null)) {
return null;
}
// follow the execution path in looking for the object.
AbstractSession parentSession = unitOfWork.getParentIdentityMapSession(this);
// assert parentSession != unitOfWork;
result = checkEarlyReturn(parentSession, translationRow);
if (result != null) {
// Optimization: If find deleted object by exact primary key
// treat this as cache hit but return null. Bug 2782991.
if (result == InvalidObject.instance) {
return result;
}
Object clone = registerResultInUnitOfWork(result, unitOfWork, translationRow, false);
if (shouldConformResultsInUnitOfWork() && unitOfWork.isObjectDeleted(clone)) {
return InvalidObject.instance;
}
return clone;
} else {
return null;
}
}
/**
* INTERNAL:
* Check to see if this query needs to be prepare and prepare it.
* The prepare is done on the original query to ensure that the work is not repeated.
*/
@Override
public void checkPrepare(AbstractSession session, AbstractRecord translationRow, boolean force) {
// CR#3823735 For custom queries the prePrepare may not have been called yet.
if (!this.isPrePrepared || (this.descriptor == null)) {
checkPrePrepare(session);
}
super.checkPrepare(session, translationRow, force);
}
/**
* INTERNAL:
* ObjectLevelReadQueries now have an explicit pre-prepare stage, which
* is for checking for pessimistic locking, and computing any joined
* attributes declared on the descriptor.
*/
public void checkPrePrepare(AbstractSession session) {
try {
// This query is first prepared for global common state, this must be synced.
if (!this.isPrePrepared) {// Avoid the monitor is already prePrepare, must check again for concurrency.
synchronized (this) {
if (!isPrePrepared()) {
AbstractSession alreadySetSession = getSession();
setSession(session);// Session is required for some init stuff.
prePrepare();
setSession(alreadySetSession);
setIsPrePrepared(true);// MUST not set prepare until done as other thread may hit before finishing the prePrepare.
}
}
} else if (this.descriptor == null) {
// Must always check descriptor as transient for remote.
checkDescriptor(session);
}
} catch (QueryException knownFailure) {
// Set the query, as preprepare can be called directly.
if (knownFailure.getQuery() == null) {
knownFailure.setQuery(this);
knownFailure.setSession(session);
}
throw knownFailure;
}
}
/**
* INTERNAL:
* The reference class has been changed, need to reset the
* descriptor. Null out the current descriptor and call
* checkDescriptor
* Added Feb 27, 2001 JED for EJBQL feature
*/
public void changeDescriptor(AbstractSession theSession) {
setDescriptor(null);
checkDescriptor(theSession);
}
/**
* INTERNAL:
* Conforms and registers an individual result. This instance could be one
* of the elements returned from a read all query, the result of a Read Object
* query, or an element read from a cursor.
* <p>
* A result needs to be registered before it can be conformed, so
* registerIndividualResult is called here.
* <p>
* Conforming on a result from the database is lenient. Since the object
* matched the query on the database we assume it matches here unless we can
* determine for sure that it was changed in this UnitOfWork not to conform.
* @param clone the clone to return
* @param arguments the parameters this query was executed with
* @param selectionCriteriaClone the expression to conform to. If was a
* selection object or key, null (which all conform to) is used
* @param alreadyReturned a hashtable of objects already found by scanning
* the UnitOfWork cache for conforming instances. Prevents duplicates.
* @param unitOfWork current UnitOfWork
* @return a clone, or null if result does not conform.
*/
protected Object conformIndividualResult(Object clone, UnitOfWorkImpl unitOfWork, AbstractRecord arguments, Expression selectionCriteriaClone, Map alreadyReturned) {
if (this.descriptor.hasWrapperPolicy() && this.descriptor.getWrapperPolicy().isWrapped(clone)) {
// The only time the clone could be wrapped is if we are not registering
// results in the unitOfWork and we are ready to return a final
// (unregistered) result now. Any further processing may accidentally
// cause it to get registered.
return clone;
}
//bug 4459976 in order to maintain backward compatibility on ordering
// lets use the result as a guild for the final result not the hashtable
// of found objects.
if (unitOfWork.isObjectDeleted(clone) ) {
return null;
}
// No need to conform if no expression, or primary key query.
if (!isExpressionQuery() || (selectionCriteriaClone == null) || isPrimaryKeyQuery()) {
if (alreadyReturned != null) {
alreadyReturned.remove(clone);
}
return clone;
}
try {
// pass in the policy to assume that the object conforms if indirection is not triggered. This
// is valid because the query returned the object and we should trust the query that the object
// matches the selection criteria, and because the indirection is not triggered then the customer
//has not changed the value.
// bug 2637555
// unless for bug 3568141 use the painstaking shouldTriggerIndirection if set
int policy = getInMemoryQueryIndirectionPolicyState();
if (policy != InMemoryQueryIndirectionPolicy.SHOULD_TRIGGER_INDIRECTION) {
policy = InMemoryQueryIndirectionPolicy.SHOULD_IGNORE_EXCEPTION_RETURN_CONFORMED;
}
if (selectionCriteriaClone.doesConform(clone, unitOfWork, arguments, policy)) {
if (alreadyReturned != null) {
alreadyReturned.remove(clone);
}
return clone;
}
} catch (QueryException exception) {
// bug 3570561: mask all-pervasive valueholder exceptions while conforming
if ((unitOfWork.getShouldThrowConformExceptions() == UnitOfWorkImpl.THROW_ALL_CONFORM_EXCEPTIONS) && (exception.getErrorCode() != QueryException.MUST_INSTANTIATE_VALUEHOLDERS)) {
throw exception;
}
if (alreadyReturned != null) {
alreadyReturned.remove(clone);
}
return clone;
}
return null;
}
/**
* PUBLIC:
* The cache will checked completely, if the object is not found the database will be queried,
* and the database result will be verified with what is in the cache and/or unit of work including new objects.
* This can lead to poor performance so it is recommended that only the database be queried in most cases.
* Queries can be configured to use the cache at several levels.
* Other caching option are available.
* @see #setCacheUsage(int)
*/
public void conformResultsInUnitOfWork() {
setCacheUsage(ConformResultsInUnitOfWork);
}
/**
* PUBLIC:
* Set the query not to lock.
*/
public void dontAcquireLocks() {
setLockMode(NO_LOCK);
}
/**
* PUBLIC:
* This can be used to explicitly disable the cache hit.
* The cache hit may not be desired in some cases, such as
* stored procedures that accept the primary key but do not query on it.
*/
public void dontCheckCache() {
setCacheUsage(DoNotCheckCache);
}
/**
* PUBLIC:
* When unset means perform read normally and dont do refresh.
*/
public void dontRefreshIdentityMapResult() {
setShouldRefreshIdentityMapResult(false);
}
/**
* PUBLIC:
* When unset means perform read normally and dont do refresh.
*/
public void dontRefreshRemoteIdentityMapResult() {
setShouldRefreshRemoteIdentityMapResult(false);
}
/**
* ADVANCED:
* If a distinct has been set the DISTINCT clause will be printed.
* This is used internally by EclipseLink for batch reading but may also be
* used directly for advanced queries or report queries.
*/
public void dontUseDistinct() {
setDistinctState(DONT_USE_DISTINCT);
//Bug2804042 Must un-prepare if prepared as the SQL may change.
setIsPrepared(false);
}
/**
* INTERNAL:
* There is a very special case where a query may be a bean-level
* pessimistic locking query.
* <p>
* If that is so, only queries executed inside of a UnitOfWork should
* have a locking clause. In the extremely rare case that we execute
* a locking query outside of a UnitOfWork, must disable locking so that
* we do not get a fetch out of sequence error.
*/
public DatabaseQuery prepareOutsideUnitOfWork(AbstractSession session) {
// Implementation is complicated because: if locking refresh will be
// auto set to true preventing cache hit.
// Must prepare this query from scratch if outside uow but locking
// Must not reprepare this query as a NO_LOCK, but create a clone first
// Must not cloneAndUnPrepare unless really have to
if (isLockQuery(session) && getLockingClause().isForUpdateOfClause()) {
ObjectLevelReadQuery clone = (ObjectLevelReadQuery)clone();
clone.setIsExecutionClone(true);
clone.dontAcquireLocks();
clone.setIsPrepared(false);
clone.checkPrePrepare(session);
return clone;
}
return this;
}
/**
* INTERNAL:
* Execute the query. If there are objects in the cache return the results
* of the cache lookup.
*
* @param session - the session in which the receiver will be executed.
* @exception DatabaseException - an error has occurred on the database.
* @exception OptimisticLockException - an error has occurred using the optimistic lock feature.
* @return An object, the result of executing the query.
*/
@Override
public Object execute(AbstractSession session, AbstractRecord translationRow) throws DatabaseException, OptimisticLockException {
//Bug#2839852 Refreshing is not possible if the query uses checkCacheOnly.
if (shouldRefreshIdentityMapResult() && shouldCheckCacheOnly()) {
throw QueryException.refreshNotPossibleWithCheckCacheOnly(this);
}
return super.execute(session, translationRow);
}
/**
* INTERNAL:
* Executes the prepared query on the datastore.
*/
@Override
public Object executeDatabaseQuery() throws DatabaseException {
// PERF: If the query has been set to optimize building its result
// directly from the database result-set then follow an optimized path.
if (this.isResultSetOptimizedQuery) {
return executeObjectLevelReadQueryFromResultSet();
}
if (this.session.isUnitOfWork()) {
UnitOfWorkImpl unitOfWork = (UnitOfWorkImpl)this.session;
// Note if a nested unit of work this will recursively start a
// transaction early on the parent also.
if (isLockQuery()) {
if ((!unitOfWork.getCommitManager().isActive()) && (!unitOfWork.wasTransactionBegunPrematurely())) {
unitOfWork.beginTransaction();
unitOfWork.setWasTransactionBegunPrematurely(true);
}
}
if (unitOfWork.isNestedUnitOfWork()) {
UnitOfWorkImpl nestedUnitOfWork = (UnitOfWorkImpl)this.session;
setSession(nestedUnitOfWork.getParent());
Object result = executeDatabaseQuery();
setSession(nestedUnitOfWork);
return registerResultInUnitOfWork(result, nestedUnitOfWork, getTranslationRow(), false);
}
}
this.session.validateQuery(this);// this will update the query with any settings
if (this.queryId == 0) {
this.queryId = this.session.getNextQueryId();
}
Object result = executeObjectLevelReadQuery();
if (result != null) {
if (getLoadGroup() != null) {
Object resultToLoad = result;
if (this.shouldIncludeData) {
resultToLoad = ((ComplexQueryResult)result).getResult();
}
session.load(resultToLoad, getLoadGroup(), getDescriptor(), false);
} else {
FetchGroup executionFetchGroup = getExecutionFetchGroup();
if (executionFetchGroup != null) {
LoadGroup lg = executionFetchGroup.toLoadGroupLoadOnly();
if (lg != null) {
Object resultToLoad = result;
if (this.shouldIncludeData) {
resultToLoad = ((ComplexQueryResult)result).getResult();
}
session.load(resultToLoad, lg, getDescriptor(), true);
}
}
}
}
return result;
}
/**
* Executes the prepared query on the datastore.
*/
protected abstract Object executeObjectLevelReadQuery() throws DatabaseException;
/**
* Executes the prepared query on the datastore.
*/
protected abstract Object executeObjectLevelReadQueryFromResultSet() throws DatabaseException;
/**
* INTERNAL:
* Execute the query in the unit of work.
* This allows any pre-execute checks to be done for unit of work queries.
*/
@Override
public Object executeInUnitOfWork(UnitOfWorkImpl unitOfWork, AbstractRecord translationRow) throws DatabaseException, OptimisticLockException {
Object result = null;
if (!shouldMaintainCache() || isReadOnly()) {
result = unitOfWork.getParent().executeQuery(this, translationRow);
} else {
result = execute(unitOfWork, translationRow);
}
// If a lockModeType was set (from JPA) we need to check if we need
// to perform a force update to the version field.
if (lockModeType != null && result != null) {
if (lockModeType.equals(READ) || lockModeType.equals(WRITE) || lockModeType.contains(OPTIMISTIC) || lockModeType.equals(PESSIMISTIC_FORCE_INCREMENT)) {
boolean forceUpdateToVersionField = lockModeType.equals(WRITE) || lockModeType.equals(OPTIMISTIC_FORCE_INCREMENT) || lockModeType.equals(PESSIMISTIC_FORCE_INCREMENT);
if (result instanceof Collection) {
Iterator i = ((Collection) result).iterator();
while (i.hasNext()) {
Object obj = i.next();
if (obj != null) {
// If it is a report query the result could be an array of objects. Must
// also deal with null results.
if (obj instanceof Object[]) {
for (Object o : (Object[]) obj) {
if (o != null && unitOfWork.isObjectRegistered(o)) {
unitOfWork.forceUpdateToVersionField(o, forceUpdateToVersionField);
}
}
} else if(unitOfWork.isObjectRegistered(obj)){
unitOfWork.forceUpdateToVersionField(obj, forceUpdateToVersionField);
}
}
}
} else if(unitOfWork.isObjectRegistered(result)) {
unitOfWork.forceUpdateToVersionField(result, forceUpdateToVersionField);
}
}
}
return result;
}
/**
* INTERNAL:
* Additional fields can be added to a query. This is used in m-m batch reading to bring back the key from the join table.
*/
public List<Object> getAdditionalFields() {
if (this.additionalFields == null) {
this.additionalFields = new ArrayList<Object>();
}
return this.additionalFields;
}
/**
* ADVANCED:
* Answers the past time this query is as of.
* @return An immutable object representation of the past time.
* <code>null</code> if no clause set, <code>AsOfClause.NO_CLAUSE</code> if
* clause explicitly set to <code>null</code>.
* @see org.eclipse.persistence.history.AsOfClause
* @see #setAsOfClause(org.eclipse.persistence.history.AsOfClause)
* @see #hasAsOfClause
*/
public AsOfClause getAsOfClause() {
return (defaultBuilder != null) ? defaultBuilder.getAsOfClause() : null;
}
/**
* PUBLIC:
* Return the cache usage.
* By default only primary key read object queries will first check the cache before accessing the database.
* Any query can be configure to query against the cache completely, by key or ignore the cache check.
* <p>Valid values are:
* <ul>
* <li> DoNotCheckCache
* <li> CheckCacheByExactPrimaryKey
* <li> CheckCacheByPrimaryKey
* <li> CheckCacheThenDatabase
* <li> CheckCacheOnly
* <li> ConformResultsInUnitOfWork
* <li> UseDescriptorSetting
* Note: UseDescriptorSetting functions like CheckCacheByPrimaryKey, except checks the appropriate descriptor's
* shouldDisableCacheHits setting when querying on the cache.
* </ul>
*/
public int getCacheUsage() {
return cacheUsage;
}
/**
* ADVANCED:
* If a distinct has been set the DISTINCT clause will be printed.
* This is used internally by EclipseLink for batch reading but may also be
* used directly for advanced queries or report queries.
*/
public short getDistinctState() {
return distinctState;
}
/**
* PUBLIC:
* This method returns the current example object. The "example" object is an actual domain object, provided
* by the client, from which an expression is generated.
* This expression is used for a query of all objects from the same class, that match the attribute values of
* the "example" object.
*/
public Object getExampleObject() {
if (getQueryMechanism().isQueryByExampleMechanism()) {
return ((QueryByExampleMechanism)getQueryMechanism()).getExampleObject();
} else {
return null;
}
}
/**
* REQUIRED:
* Get the expression builder which should be used for this query.
* This expression builder should be used to build all expressions used by this query.
*/
public ExpressionBuilder getExpressionBuilder() {
if (defaultBuilder == null) {
initializeDefaultBuilder();
}
return defaultBuilder;
}
/**
* INTERNAL
* Sets the default expression builder for this query.
*/
public void setExpressionBuilder(ExpressionBuilder builder) {
this.defaultBuilder = builder;
}
/**
* PUBLIC:
* Returns the InMemoryQueryIndirectionPolicy for this query
*/
public int getInMemoryQueryIndirectionPolicyState() {
return this.inMemoryQueryIndirectionPolicy;
}
/**
* PUBLIC:
* Returns the InMemoryQueryIndirectionPolicy for this query
*/
public InMemoryQueryIndirectionPolicy getInMemoryQueryIndirectionPolicy() {
return new InMemoryQueryIndirectionPolicy(inMemoryQueryIndirectionPolicy, this);
}
/**
* INTERNAL:
* Return join manager responsible for managing all aspects of joining for the query.
* Queries without joining should not have a joinedAttributeManager.
*/
public JoinedAttributeManager getJoinedAttributeManager() {
if (this.joinedAttributeManager == null) {
this.joinedAttributeManager = new JoinedAttributeManager(getDescriptor(), getExpressionBuilder(), this);
}
return this.joinedAttributeManager;
}
/**
* INTERNAL:
* Set join manager responsible for managing all aspects of joining for the query.
*/
public void setJoinedAttributeManager(JoinedAttributeManager joinedAttributeManager) {
this.joinedAttributeManager = joinedAttributeManager;
}
/**
* INTERNAL:
* Return if any attributes are joined.
* To avoid the initialization of the JoinedAttributeManager this should be first checked before accessing.
*/
public boolean hasJoining() {
return this.joinedAttributeManager != null;
}
/**
* INTERNAL:
* Convenience method for project mapping.
*/
public List getJoinedAttributeExpressions() {
return getJoinedAttributeManager().getJoinedAttributeExpressions();
}
/**
* INTERNAL:
* Convenience method for project mapping.
*/
public void setJoinedAttributeExpressions(List expressions) {
if (((expressions != null) && !expressions.isEmpty()) || hasJoining()) {
getJoinedAttributeManager().setJoinedAttributeExpressions_(expressions);
}
}
/**
* INTERNAL:
* Return the order expressions for the query.
*/
public List<Expression> getOrderByExpressions() {
if (orderByExpressions == null) {
orderByExpressions = new ArrayList<Expression>();
}
return orderByExpressions;
}
/**
* INTERNAL:
* Set the order expressions for the query.
*/
public void setOrderByExpressions(List<Expression> orderByExpressions) {
this.orderByExpressions = orderByExpressions;
}
/**
* INTERNAL:
* The order bys are lazy initialized to conserve space.
*/
public boolean hasOrderByExpressions() {
return (orderByExpressions != null) && (!orderByExpressions.isEmpty());
}
/**
* INTERNAL:
* The unions are lazy initialized to conserve space.
*/
public boolean hasUnionExpressions() {
return (unionExpressions != null) && (!unionExpressions.isEmpty());
}
/**
* PUBLIC:
* Return if duplicate rows should be filter when using 1-m joining.
*/
public boolean shouldFilterDuplicates() {
if (hasJoining()) {
return getJoinedAttributeManager().shouldFilterDuplicates();
}
return true;
}
/**
* PUBLIC:
* Set if duplicate rows should be filter when using 1-m joining.
*/
public void setShouldFilterDuplicates(boolean shouldFilterDuplicates) {
getJoinedAttributeManager().setShouldFilterDuplicates(shouldFilterDuplicates);
}
/**
* INTERNAL:
* It is not exactly as simple as a query being either locking or not.
* Any combination of the reference class object and joined attributes
* may be locked.
*/
public ForUpdateClause getLockingClause() {
return lockingClause;
}
/**
* INTERNAL:
* Return the attributes that must be joined, but not fetched, that is,
* do not trigger the value holder.
*/
public List<Expression> getNonFetchJoinAttributeExpressions() {
if (this.nonFetchJoinAttributeExpressions == null){
this.nonFetchJoinAttributeExpressions = new ArrayList<Expression>();
}
return nonFetchJoinAttributeExpressions;
}
/**
* INTERNAL:
* Return the partial attributes to select.
*/
public List<Expression> getPartialAttributeExpressions() {
if (this.partialAttributeExpressions == null) {
this.partialAttributeExpressions = new ArrayList<Expression>();
}
return this.partialAttributeExpressions;
}
/**
* PUBLIC:
* When using Query By Example, an instance of QueryByExamplePolicy is used to customize the query.
* The policy is useful when special operations are to be used for comparisons (notEqual, lessThan,
* greaterThan, like etc.), when a certain value is to be ignored, or when dealing with nulls.
*/
public QueryByExamplePolicy getQueryByExamplePolicy() {
if (getQueryMechanism().isQueryByExampleMechanism()) {
return ((QueryByExampleMechanism)getQueryMechanism()).getQueryByExamplePolicy();
} else {
return null;
}
}
/**
* PUBLIC:
* Return the reference class of the query.
*/
@Override
public Class getReferenceClass() {
return referenceClass;
}
/**
* INTERNAL:
* Return the reference class of the query.
*/
public String getReferenceClassName() {
if ((referenceClassName == null) && (referenceClass != null)) {
referenceClassName = referenceClass.getName();
}
return referenceClassName;
}
/**
* PUBLIC:
* Answers if the domain objects are to be read as of a past time.
* @see #getAsOfClause
*/
public boolean hasAsOfClause() {
return ((defaultBuilder != null) && defaultBuilder.hasAsOfClause());
}
/**
* INTERNAL:
* Return the attributes that must be joined.
*/
public boolean hasNonFetchJoinedAttributeExpressions() {
return this.nonFetchJoinAttributeExpressions != null && !this.nonFetchJoinAttributeExpressions.isEmpty();
}
/**
* INTERNAL:
* Return if partial attributes.
*/
public boolean hasPartialAttributeExpressions() {
return (this.partialAttributeExpressions != null) && (!this.partialAttributeExpressions.isEmpty());
}
/**
* INTERNAL:
* Return if additional field.
*/
public boolean hasAdditionalFields() {
return (this.additionalFields != null) && (!this.additionalFields.isEmpty());
}
/**
* INTERNAL:
* Return the fields required in the select clause, for patial attribute reading.
*/
public Vector getPartialAttributeSelectionFields(boolean isCustomSQL) {
Vector localFields = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance(getPartialAttributeExpressions().size());
Vector foreignFields = null;
//Add primary key and indicator fields.
localFields.addAll(getDescriptor().getPrimaryKeyFields());
if (getDescriptor().hasInheritance() && (getDescriptor().getInheritancePolicy().getClassIndicatorField() != null)) {
localFields.addElement(getDescriptor().getInheritancePolicy().getClassIndicatorField());
}
//Add attribute fields
for(Iterator it = getPartialAttributeExpressions().iterator();it.hasNext();){
Expression expression = (Expression)it.next();
if (expression.isQueryKeyExpression()) {
((QueryKeyExpression)expression).getBuilder().setSession(session.getRootSession(null));
((QueryKeyExpression)expression).getBuilder().setQueryClass(getDescriptor().getJavaClass());
DatabaseMapping mapping = ((QueryKeyExpression)expression).getMapping();
if (!((QueryKeyExpression)expression).getBaseExpression().isExpressionBuilder()) {
if(foreignFields==null){
foreignFields = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance();
}
if(!isCustomSQL){
foreignFields.add(expression);
}else{
foreignFields.addAll(expression.getSelectionFields(this));
}
}else{
if (mapping == null) {
throw QueryException.specifiedPartialAttributeDoesNotExist(this, expression.getName(), descriptor.getJavaClass().getName());
}
if(mapping.isForeignReferenceMapping() ){
if(foreignFields==null){
foreignFields = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance();
}
if(!isCustomSQL){
foreignFields.add(expression);
}else{
foreignFields.addAll(expression.getSelectionFields(this));
}
}else{
localFields.addAll(expression.getSelectionFields(this));
}
}
} else {
throw QueryException.expressionDoesNotSupportPartialAttributeReading(expression);
}
}
//Build fields in same order as the fields of the descriptor to ensure field and join indexes match.
Vector selectionFields = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance();
for (Iterator iterator = getDescriptor().getFields().iterator(); iterator.hasNext();) {
DatabaseField field = (DatabaseField)iterator.next();
if (localFields.contains(field)) {
selectionFields.add(field);
} else {
selectionFields.add(null);
}
}
//Combine fields list for source descriptor and target descriptor.
if(foreignFields!=null){
selectionFields.addAll(foreignFields);
}
return selectionFields;
}
/**
* INTERNAL:
* Return the set of fields required in the select clause, for fetch group reading.
*/
public Set<DatabaseField> getFetchGroupNonNestedFieldsSet() {
return getFetchGroupNonNestedFieldsSet(null);
}
/**
* INTERNAL:
* Return the set of fields required in the select clause, for fetch group reading.
*/
public Set<DatabaseField> getFetchGroupNonNestedFieldsSet(DatabaseMapping nestedMapping) {
Set fetchedFields = new HashSet(getExecutionFetchGroup().getAttributeNames().size());
// Add required fields.
fetchedFields.addAll(getDescriptor().getPrimaryKeyFields());
if (getDescriptor().hasInheritance() && (getDescriptor().getInheritancePolicy().getClassIndicatorField() != null)) {
fetchedFields.add(getDescriptor().getInheritancePolicy().getClassIndicatorField());
}
if (shouldMaintainCache() && getDescriptor().usesOptimisticLocking()) {
DatabaseField lockField = getDescriptor().getOptimisticLockingPolicy().getWriteLockField();
if (lockField != null) {
fetchedFields.add(lockField);
}
}
// Add specified fields.
for (Iterator iterator = getExecutionFetchGroup().getAttributeNames().iterator(); iterator.hasNext();) {
String attribute = (String)iterator.next();
DatabaseMapping mapping = getDescriptor().getObjectBuilder().getMappingForAttributeName(attribute);
if (mapping == null) {
throw QueryException.fetchGroupAttributeNotMapped(attribute);
}
fetchedFields.addAll(mapping.getFields());
}
if ((nestedMapping != null) && nestedMapping.isCollectionMapping()) {
List<DatabaseField> additionalFields = nestedMapping.getContainerPolicy().getAdditionalFieldsForJoin((CollectionMapping)nestedMapping);
if(additionalFields != null) {
fetchedFields.addAll(additionalFields);
}
}
return fetchedFields;
}
/**
* INTERNAL:
* Return the fields required in the select clause, for fetch group reading.
*/
public List<DatabaseField> getFetchGroupSelectionFields() {
return getFetchGroupSelectionFields(null);
}
/**
* INTERNAL:
* Return the fields required in the select clause, for fetch group reading.
* Top level (not nested) passes null instead of nestedMapping.
*/
protected List<DatabaseField> getFetchGroupSelectionFields(DatabaseMapping nestedMapping) {
Set<DatabaseField> fetchedFields = getFetchGroupNonNestedFieldsSet(nestedMapping);
// Build field list in the same order as descriptor's fields so that the fields printed in the usual order in SELECT clause.
List<DatabaseField> fields = new ArrayList(fetchedFields.size());
for (Iterator iterator = getDescriptor().getFields().iterator(); iterator.hasNext();) {
DatabaseField field = (DatabaseField)iterator.next();
if (fetchedFields.contains(field)) {
fields.add(field);
}
}
return fields;
}
/**
* INTERNAL:
* The method adds to the passed input vector the
* fields or expressions corresponding to the joins.
*/
public void addJoinSelectionFields(Vector fields, boolean isCustomSQL) {
// executiveFetchGroup is used for warnings only - always null if no warnings logged
FetchGroup executionFetchGroup = null;
if(session.shouldLog(SessionLog.WARNING, SessionLog.QUERY)) {
executionFetchGroup = getExecutionFetchGroup();
}
for(Expression expression : getJoinedAttributeManager().getJoinedAttributeExpressions()) {
addSelectionFieldsForJoinedExpression(fields, isCustomSQL, expression);
// executiveFetchGroup is used for warnings only - always null if no warnings logged
if(executionFetchGroup != null) {
String nestedAttributeName = ((QueryKeyExpression)expression).getNestedAttributeName();
if(nestedAttributeName != null) {
if(!executionFetchGroup.containsAttributeInternal(nestedAttributeName)) {
getSession().log(SessionLog.WARNING, SessionLog.QUERY, "query_has_joined_attribute_outside_fetch_group", new Object[]{toString(), nestedAttributeName});
}
}
}
}
for(Expression expression : getJoinedAttributeManager().getJoinedMappingExpressions()) {
addSelectionFieldsForJoinedExpression(fields, isCustomSQL, expression);
}
}
/**
* INTERNAL:
* Return the fields selected by the query.
* This includes the partial or joined fields.
* This is only used for custom SQL executions.
*/
public Vector getSelectionFields() {
if (hasPartialAttributeExpressions()) {
return getPartialAttributeSelectionFields(true);
}
Vector fields = NonSynchronizedVector.newInstance();
if (getExecutionFetchGroup() != null) {
fields.addAll(getFetchGroupSelectionFields());
} else {
fields.addAll(getDescriptor().getAllSelectionFields(this));
}
// Add joined fields.
if (hasJoining()) {
addJoinSelectionFields(fields, true);
}
if (hasAdditionalFields()) {
// Add additional fields, use for batch reading m-m.
fields.addAll(getAdditionalFields());
}
return fields;
}
/**
* PUBLIC:
* Return the WAIT timeout value of pessimistic locking query.
*/
public Integer getWaitTimeout() {
return waitTimeout;
}
public TimeUnit getWaitTimeoutUnit() {
return waitTimeoutUnit;
}
/**
* Initialize the expression builder which should be used for this query. If
* there is a where clause, use its expression builder, otherwise
* generate one and cache it. This helps avoid unnecessary rebuilds.
*/
protected void initializeDefaultBuilder() {
DatabaseQueryMechanism mech = getQueryMechanism();
if (mech.isExpressionQueryMechanism() && ((ExpressionQueryMechanism)mech).getExpressionBuilder() != null) {
this.defaultBuilder = ((ExpressionQueryMechanism)mech).getExpressionBuilder();
if (this.defaultBuilder.getQueryClass() != null && !this.defaultBuilder.getQueryClass().equals(this.referenceClass)){
this.defaultBuilder = new ExpressionBuilder();
}
return;
}
this.defaultBuilder = new ExpressionBuilder();
}
/**
* INTERNAL:
* return true if this query has computed its distinct value already
*/
public boolean isDistinctComputed() {
return this.distinctState != UNCOMPUTED_DISTINCT;
}
/**
* PUBLIC:
* Answers if the query lock mode is known to be LOCK or LOCK_NOWAIT.
*
* In the case of DEFAULT_LOCK_MODE and the query reference class being a CMP entity bean,
* at execution time LOCK, LOCK_NOWAIT, or NO_LOCK will be decided.
* <p>
* If a single joined attribute was configured for pessimistic locking then
* this will return true (after first execution) as the SQL contained a
* FOR UPDATE OF clause.
*/
public boolean isLockQuery() {
return (this.lockingClause != null) && (getLockMode() > NO_LOCK);
}
/**
* ADVANCED:
* Answers if this query will issue any pessimistic locks.
* <p>
* If the lock mode is not known (DEFAULT_LOCK_MODE / descriptor specified
* fine-grained locking) the lock mode will be determined now, to be either
* LOCK, LOCK_NOWAIT, or NO_LOCK.
* @see #isLockQuery()
*/
public boolean isLockQuery(org.eclipse.persistence.sessions.Session session) {
checkPrePrepare((AbstractSession)session);
return isLockQuery();
}
/**
* PUBLIC:
* Return if this is an object level read query.
*/
@Override
public boolean isObjectLevelReadQuery() {
return true;
}
/**
* INTERNAL:
* Return if partial attribute.
*/
public boolean isPartialAttribute(String attributeName) {
if (this.partialAttributeExpressions == null) {
return false;
}
List<Expression> partialAttributeExpressions = getPartialAttributeExpressions();
int size = partialAttributeExpressions.size();
for (int index = 0; index < size; index++) {
QueryKeyExpression expression = (QueryKeyExpression)partialAttributeExpressions.get(index);
while (!expression.getBaseExpression().isExpressionBuilder()) {
expression = (QueryKeyExpression)expression.getBaseExpression();
}
if (expression.getName().equals(attributeName)) {
return true;
}
}
return false;
}
/**
* INTERNAL:
* Indicates whether pessimistic lock should also be applied to relation tables (ManyToMany and OneToOne mappings),
* reference tables (DirectCollection and AggregateCollection mapping).
*/
public boolean shouldExtendPessimisticLockScope() {
return shouldExtendPessimisticLockScope;
}
/**
* PUBLIC:
* Queries prepare common stated in themselves.
*/
protected boolean isPrePrepared() {
return isPrePrepared;
}
/**
* INTERNAL:
* If changes are made to the query that affect the derived SQL or Call
* parameters the query needs to be prepared again.
* <p>
* Automatically called internally.
* <p>
* The early phase of preparation is to check if this is a pessimistic
* locking query.
*/
public void setIsPrePrepared(boolean isPrePrepared) {
// Only unprepare if was prepared to begin with, prevent unpreparing during prepare.
if (this.isPrePrepared && !isPrePrepared) {
setIsPrepared(false);
if (hasJoining()) {
getJoinedAttributeManager().reset();
}
}
this.isPrePrepared = isPrePrepared;
}
/**
* INTERNAL:
* Indicates whether pessimistic lock should also be applied to relation tables (ManyToMany and OneToOne mappings),
* reference tables (DirectCollection and AggregateCollection mapping).
*/
public void setShouldExtendPessimisticLockScope(boolean isExtended) {
shouldExtendPessimisticLockScope = isExtended;
}
/**
* INTERNAL:
* Clear cached flags when un-preparing.
*/
public void setIsPrepared(boolean isPrepared) {
boolean oldIsPrepared = this.isPrepared;
super.setIsPrepared(isPrepared);
if (!isPrepared) {
// when the query is cached is not yet prepared and while the query is prepared setIsPrepared(false) may be called.
// the intention is to remove the query from cache when it has been altered after prepare has completed.
if (this.isCachedExpressionQuery && oldIsPrepared) {
if (this.descriptor != null) {
this.descriptor.getQueryManager().removeCachedExpressionQuery(this);
this.isCachedExpressionQuery = false;
}
}
this.isReferenceClassLocked = null;
this.concreteSubclassCalls = null;
this.concreteSubclassQueries = null;
this.aggregateQueries = null;
this.concreteSubclassJoinedMappingIndexes = null;
}
}
/**
* INTERNAL:
* Clear cached flags when un-preparing.
* The method always keeps concrete subclass data (unlike setIsPrepared(false)).
*/
protected void setIsPreparedKeepingSubclassData(boolean isPrepared) {
super.setIsPrepared(isPrepared);
if (!isPrepared) {
this.isReferenceClassLocked = null;
}
}
/**
* INTERNAL:
* Prepare the receiver for execution in a session.
*/
@Override
protected void prepare() throws QueryException {
super.prepare();
prepareQuery();
if (hasJoining()) {
this.joinedAttributeManager.computeJoiningMappingQueries(session);
}
computeBatchReadMappingQueries();
if (getLoadGroup() != null) {
if (getLoadGroup().getIsConcurrent() == null) {
getLoadGroup().setIsConcurrent(getSession().isConcurrent());
}
}
}
/**
* INTERNAL:
* Check if the query is cached and prepare from it.
* Return true if the query was cached.
*/
protected boolean prepareFromCachedQuery() {
// PERF: Check if the equivalent expression query has already been prepared.
// Only allow queries with default properties to be cached.
boolean isCacheable = isExpressionQuery() && (!getQueryMechanism().isJPQLCallQueryMechanism()) && isDefaultPropertiesQuery() && (!getSession().isHistoricalSession());
DatabaseQuery cachedQuery = null;
if (isCacheable) {
cachedQuery = this.descriptor.getQueryManager().getCachedExpressionQuery(this);
} else {
return false;
}
if ((cachedQuery != null) && cachedQuery.isPrepared()) {
prepareFromQuery(cachedQuery);
setIsPrepared(true);
return true;
}
this.descriptor.getQueryManager().putCachedExpressionQuery(this);
this.isCachedExpressionQuery = true;
this.isExecutionClone = false;
return false;
}
/**
* INTERNAL:
* Copy all setting from the query.
* This is used to morph queries from one type to the other.
* By default this calls prepareFromQuery, but additional properties may be required
* to be copied as prepareFromQuery only copies properties that affect the SQL.
*/
@Override
public void copyFromQuery(DatabaseQuery query) {
super.copyFromQuery(query);
if (query.isObjectLevelReadQuery()) {
ObjectLevelReadQuery readQuery = (ObjectLevelReadQuery)query;
this.cacheUsage = readQuery.cacheUsage;
this.isReadOnly = readQuery.isReadOnly;
this.isResultSetOptimizedQuery = readQuery.isResultSetOptimizedQuery;
this.shouldIncludeData = readQuery.shouldIncludeData;
this.inMemoryQueryIndirectionPolicy = readQuery.inMemoryQueryIndirectionPolicy;
this.lockModeType = readQuery.lockModeType;
this.defaultBuilder = readQuery.defaultBuilder;
this.distinctState = readQuery.distinctState;
this.shouldUseSerializedObjectPolicy = readQuery.shouldUseSerializedObjectPolicy;
}
}
/**
* INTERNAL:
* Prepare the query from the prepared query.
* This allows a dynamic query to prepare itself directly from a prepared query instance.
* This is used in the EJBQL parse cache to allow preparsed queries to be used to prepare
* dynamic queries.
* This only copies over properties that are configured through EJBQL.
*/
@Override
public void prepareFromQuery(DatabaseQuery query) {
super.prepareFromQuery(query);
if (query.isObjectLevelReadQuery()) {
ObjectLevelReadQuery objectQuery = (ObjectLevelReadQuery)query;
this.referenceClass = objectQuery.referenceClass;
this.distinctState = objectQuery.distinctState;
if (objectQuery.hasJoining()) {
getJoinedAttributeManager().copyFrom(objectQuery.getJoinedAttributeManager());
}
if (objectQuery.hasBatchReadAttributes()) {
this.batchFetchPolicy = objectQuery.getBatchFetchPolicy().clone();
}
this.nonFetchJoinAttributeExpressions = objectQuery.nonFetchJoinAttributeExpressions;
this.defaultBuilder = objectQuery.defaultBuilder;
this.fetchGroup = objectQuery.fetchGroup;
this.fetchGroupName = objectQuery.fetchGroupName;
this.isReferenceClassLocked = objectQuery.isReferenceClassLocked;
this.shouldOuterJoinSubclasses = objectQuery.shouldOuterJoinSubclasses;
this.shouldUseDefaultFetchGroup = objectQuery.shouldUseDefaultFetchGroup;
this.concreteSubclassCalls = objectQuery.concreteSubclassCalls;
this.concreteSubclassQueries = objectQuery.concreteSubclassQueries;
this.aggregateQueries = objectQuery.aggregateQueries;
this.concreteSubclassJoinedMappingIndexes = objectQuery.concreteSubclassJoinedMappingIndexes;
this.additionalFields = objectQuery.additionalFields;
this.partialAttributeExpressions = objectQuery.partialAttributeExpressions;
if (objectQuery.hasOrderByExpressions()) {
this.orderByExpressions = objectQuery.orderByExpressions;
}
if (objectQuery.hasUnionExpressions()) {
this.unionExpressions = objectQuery.unionExpressions;
}
}
}
/**
* INTERNAL:
* Add mandatory attributes to fetch group, create entityFetchGroup.
*/
public void prepareFetchGroup() throws QueryException {
FetchGroupManager fetchGroupManager = this.descriptor.getFetchGroupManager();
if (fetchGroupManager != null) {
if (this.fetchGroup == null) {
if (this.fetchGroupName != null) {
this.fetchGroup = fetchGroupManager.getFetchGroup(this.fetchGroupName);
} else if (this.shouldUseDefaultFetchGroup) {
this.fetchGroup = this.descriptor.getFetchGroupManager().getDefaultFetchGroup();
}
}
if (this.fetchGroup != null) {
if (hasPartialAttributeExpressions()) {
//fetch group does not work with partial attribute reading
throw QueryException.fetchGroupNotSupportOnPartialAttributeReading();
}
// currently SOP is incompatible with fetch groups
setShouldUseSerializedObjectPolicy(false);
this.descriptor.getFetchGroupManager().prepareAndVerify(this.fetchGroup);
}
} else {
// FetchGroupManager is null
if (this.fetchGroup != null || this.fetchGroupName != null) {
throw QueryException.fetchGroupValidOnlyIfFetchGroupManagerInDescriptor(getDescriptor().getJavaClassName(), getName());
}
}
}
/**
* INTERNAL:
* Prepare the receiver for execution in a session.
*/
protected void prePrepare() throws QueryException {
// For bug 3136413/2610803 building the selection criteria from an EJBQL string or
// an example object is done just in time.
buildSelectionCriteria(this.session);
checkDescriptor(this.session);
// Validate and prepare join expressions.
if (hasJoining()) {
this.joinedAttributeManager.prepareJoinExpressions(this.session);
}
prepareFetchGroup();
// Add mapping joined attributes.
if (getQueryMechanism().isExpressionQueryMechanism() && this.descriptor.getObjectBuilder().hasJoinedAttributes()) {
getJoinedAttributeManager().processJoinedMappings(this.session);
if (this.joinedAttributeManager.hasOrderByExpressions()) {
for (Expression orderBy : this.joinedAttributeManager.getOrderByExpressions()) {
addOrdering(orderBy);
}
}
if (this.joinedAttributeManager.hasAdditionalFieldExpressions()) {
for (Expression additionalField : this.joinedAttributeManager.getAdditionalFieldExpressions()) {
addAdditionalField(additionalField);
}
}
}
if (this.lockModeType != null) {
if (this.lockModeType.equals(NONE)) {
setLockMode(ObjectBuildingQuery.NO_LOCK);
} else if (this.lockModeType.contains(PESSIMISTIC_)) {
// If no wait timeout was set from a query hint, grab the
// default one from the session if one is available.
Integer timeout = (this.waitTimeout == null) ? this.session.getPessimisticLockTimeoutDefault() : this.waitTimeout;
Long convertedTimeout =null;
TimeUnit timeoutUnit = (this.waitTimeoutUnit == null) ? this.session.getPessimisticLockTimeoutUnitDefault() : this.waitTimeoutUnit;
if (timeout == null) {
setLockMode(ObjectBuildingQuery.LOCK);
} else {
if (timeout.intValue() == 0) {
setLockMode(ObjectBuildingQuery.LOCK_NOWAIT);
} else {
convertedTimeout = TimeUnit.SECONDS.convert(timeout, timeoutUnit);
if(convertedTimeout > Integer.MAX_VALUE) {
timeout = Integer.MAX_VALUE;
} else {
timeout = convertedTimeout.intValue();
}
//Round up the timeout if SECONDS are larger than the given units
if(TimeUnit.SECONDS.compareTo(timeoutUnit) > 0 && timeout % 1000 > 0) {
timeout += 1;
}
this.lockingClause = ForUpdateClause.newInstance(timeout);
}
}
}
}
// modify query for locking only if locking has not been configured
if (isDefaultLock()) {
setWasDefaultLockMode(true);
ForUpdateOfClause lockingClause = null;
if (hasJoining()) {
lockingClause = getJoinedAttributeManager().setupLockingClauseForJoinedExpressions(lockingClause, getSession());
}
if (this.descriptor.hasPessimisticLockingPolicy()) {
lockingClause = new ForUpdateOfClause();
lockingClause.setLockMode(this.descriptor.getCMPPolicy().getPessimisticLockingPolicy().getLockingMode());
lockingClause.addLockedExpression(getExpressionBuilder());
}
if (lockingClause != null) {
this.lockingClause = lockingClause;
// SPECJ: Locking not compatible with distinct for batch reading.
dontUseDistinct();
}
} else if ((getLockMode() <= NO_LOCK) && (!descriptor.hasPessimisticLockingPolicy())) {
setWasDefaultLockMode(true);
}
setRequiresDeferredLocks(DeferredLockManager.SHOULD_USE_DEFERRED_LOCKS && (hasJoining() || (this.descriptor.shouldAcquireCascadedLocks())));
if (hasJoining() && hasPartialAttributeExpressions()) {
this.session.log(SessionLog.WARNING, SessionLog.QUERY, "query_has_both_join_attributes_and_partial_attributes", new Object[]{this, getName()});
}
}
/**
* INTERNAL:
* Prepare the receiver for execution in a session.
*/
protected void prepareQuery() throws QueryException {
if ((!shouldMaintainCache()) && shouldRefreshIdentityMapResult() && (!this.descriptor.isAggregateCollectionDescriptor())) {
throw QueryException.refreshNotPossibleWithoutCache(this);
}
if (shouldMaintainCache() && hasPartialAttributeExpressions()) {
throw QueryException.cannotCachePartialObjects(this);
}
if (this.descriptor.isAggregateDescriptor()) {
// Not allowed
throw QueryException.aggregateObjectCannotBeDeletedOrWritten(this.descriptor, this);
}
if (hasAsOfClause() && (getSession().getAsOfClause() == null)) {
if (shouldMaintainCache()) {
throw QueryException.historicalQueriesMustPreserveGlobalCache();
} else if (!getSession().getPlatform().isOracle() && !getSession().getProject().hasGenericHistorySupport()) {
throw QueryException.historicalQueriesOnlySupportedOnOracle();
}
}
// Validate and prepare partial attribute expressions.
if (hasPartialAttributeExpressions()) {
for (int index = 0; index < getPartialAttributeExpressions().size(); index++) {
Expression expression = getPartialAttributeExpressions().get(index);
// Search if any of the expression traverse a 1-m.
while (expression.isQueryKeyExpression() && (!expression.isExpressionBuilder())) {
if (((QueryKeyExpression)expression).shouldQueryToManyRelationship()) {
getJoinedAttributeManager().setIsToManyJoinQuery(true);
}
expression = ((QueryKeyExpression)expression).getBaseExpression();
}
}
}
if (!shouldOuterJoinSubclasses()) {
setShouldOuterJoinSubclasses(getMaxRows()>0 || getFirstResult()>0 || (this.descriptor != null &&
this.descriptor.hasInheritance() && (this.descriptor.getInheritancePolicy().shouldOuterJoinSubclasses()|| this.getExpressionBuilder().isTreatUsed()) ));
}
// Ensure the subclass call cache is initialized if a multiple table inheritance descriptor.
// This must be initialized in the query before it is cloned, and never cloned.
if (!shouldOuterJoinSubclasses() && this.descriptor.hasInheritance()
&& this.descriptor.getInheritancePolicy().requiresMultipleTableSubclassRead()) {
getConcreteSubclassCalls();
if (hasJoining()) {
getConcreteSubclassJoinedMappingIndexes();
}
}
// Ensure the subclass call cache is initialized if a table per class inheritance descriptor.
// This must be initialized in the query before it is cloned, and never cloned.
if (this.descriptor.hasTablePerClassPolicy()
&& (this.descriptor.getTablePerClassPolicy().getChildDescriptors().size() > 0)) {
getConcreteSubclassQueries();
}
}
/**
* INTERNAL:
* Prepare the receiver for execution in a session.
*/
@Override
protected void prepareForRemoteExecution() throws QueryException {
super.prepareForRemoteExecution();
checkPrePrepare(getSession());
prepareQuery();
}
/**
* PUBLIC:
* Refresh the attributes of the object(s) resulting from the query.
* If cascading is used the private parts of the objects will also be refreshed.
*/
public void refreshIdentityMapResult() {
setShouldRefreshIdentityMapResult(true);
}
/**
* PUBLIC:
* Refresh the attributes of the object(s) resulting from the query.
* If cascading is used the private parts of the objects will also be refreshed.
*/
public void refreshRemoteIdentityMapResult() {
setShouldRefreshRemoteIdentityMapResult(true);
}
/**
* INTERNAL:
* All objects queried via a UnitOfWork get registered here. If the query
* went to the database.
* <p>
* Involves registering the query result individually and in totality, and
* hence refreshing / conforming is done here.
*
* @param result may be collection (read all) or an object (read one),
* or even a cursor. If in transaction the shared cache will
* be bypassed, meaning the result may not be originals from the parent
* but raw database rows.
* @param unitOfWork the unitOfWork the result is being registered in.
* @param arguments the original arguments/parameters passed to the query
* execution. Used by conforming
* @param buildDirectlyFromRows If in transaction must construct
* a registered result from raw database rows.
*
* @return the final (conformed, refreshed, wrapped) UnitOfWork query result
*/
public abstract Object registerResultInUnitOfWork(Object result, UnitOfWorkImpl unitOfWork, AbstractRecord arguments, boolean buildDirectlyFromRows);
/**
* ADVANCED:
* If a distinct has been set the DISTINCT clause will be printed.
* This is used internally by TopLink for batch reading but may also be
* used directly for advanced queries or report queries.
*/
public void resetDistinct() {
setDistinctState(UNCOMPUTED_DISTINCT);
}
/**
* INTERNAL:
* Additional fields can be added to a query. This is used in m-m batch reading to bring back the key from the join table.
*/
public void setAdditionalFields(List<Object> additionalFields) {
this.additionalFields = additionalFields;
}
/**
* PUBLIC:
* Return if the cache should be checked.
*/
public boolean shouldCheckCache() {
return this.cacheUsage != DoNotCheckCache;
}
/**
* PUBLIC:
* Set the cache usage.
* By default only primary key read object queries will first check the cache before accessing the database.
* Any query can be configure to query against the cache completely, by key or ignore the cache check.
* <p>Valid values are:
* <ul>
* <li> DoNotCheckCache - The query does not check the cache but accesses the database, the cache will still be maintain.
* <li> CheckCacheByExactPrimaryKey - If the query is exactly and only on the object's primary key the cache will be checked.
* <li> CheckCacheByPrimaryKey - If the query contains the primary key and possible other values the cache will be checked.
* <li> CheckCacheThenDatabase - The whole cache will be checked to see if there is any object matching the query, if not the database will be accessed.
* <li> CheckCacheOnly - The whole cache will be checked to see if there is any object matching the query, if not null or an empty collection is returned.
* <li> ConformResultsAgainstUnitOfWork - The results will be checked against the changes within the unit of work and object no longer matching or deleted will be remove, matching new objects will also be added.
* <li> shouldCheckDescriptorForCacheUsage - This setting functions like CheckCacheByPrimaryKey, except checks the appropriate descriptor's
* shouldDisableCacheHits setting when querying on the cache.
* </ul>
*/
public void setCacheUsage(int cacheUsage) {
this.cacheUsage = cacheUsage;
}
/**
* INTERNAL:
* Set the descriptor for the query.
*/
public void setDescriptor(ClassDescriptor descriptor) {
// If the descriptor changed must unprepare as the SQL may change.
if (this.descriptor != descriptor) {
setIsPreparedKeepingSubclassData(false);
this.descriptor = descriptor;
}
if (this.fetchGroup != null){
this.fetchGroup = getExecutionFetchGroup(descriptor);
}
if (this.joinedAttributeManager != null){
this.joinedAttributeManager.setDescriptor(descriptor);
}
}
/**
* ADVANCED:
* If a distinct has been set the DISTINCT clause will be printed.
* This is used internally by TopLink for batch reading but may also be
* used directly for advanced queries or report queries.
*/
public void setDistinctState(short distinctState) {
this.distinctState = distinctState;
//Bug2804042 Must un-prepare if prepared as the SQL may change.
setIsPrepared(false);
}
/**
* PUBLIC:
* Set the example object of the query to be the newExampleObject.
* The example object is used for Query By Example.
* When doing a Query By Example, an instance of the desired object is created, and the fields are filled with
* the values that are required in the result set. From these values the corresponding expression is built
* by EclipseLink, and the query is executed, returning the set of results.
* <p>If a query already has a selection criteria this criteria and the generated
* query by example criteria will be conjuncted.
* <p>Once a query is executed you must make an explicit call to setExampleObject
* if the example object is changed, so the query will know to prepare itself again.
* <p>There is a caution to setting both a selection criteria and an example object:
* Only in this case if you set the example object again after execution you must then also reset the selection criteria.
* (This is because after execution the original criteria and Query By Example criteria were fused together,
* and the former cannot be easily recovered from the now invalid result).
* <p>
* <b>Restrictions</b>:
* <ul>
* <li>Only attributes whose mappings are DirectToField, Aggregate (Embeddable), ObjectReference
* (OneToOne) or Collection type OneToMany/ManyToMany are considered in a Query By Example object. The behaviour when an example object has attribute values for other mappings types is <b>undefined</b>.
* <ul><li>To ensure the example does not include any unsupported mappings the flag {@link org.eclipse.persistence.queries.QueryByExamplePolicy#setValidateExample}
* should be set to true on the corresponding QueryByExamplePolicy to ensure no unsupported relationship types are used in the example.</li>
* <li> For OneToMany and ManyToMany mappings the elements within the collections and the references attribute values will be added to the expression as disjuncts (OR)</li>
* </ul></li>
* </ul>
*/
public void setExampleObject(Object newExampleObject) {
if (!getQueryMechanism().isQueryByExampleMechanism()) {
setQueryMechanism(new QueryByExampleMechanism(this, getSelectionCriteria()));
((QueryByExampleMechanism)getQueryMechanism()).setExampleObject(newExampleObject);
setIsPrepared(false);
} else {
((QueryByExampleMechanism)getQueryMechanism()).setExampleObject(newExampleObject);
// Potentially force the query to be prepared again. If shouldPrepare() is false
// must use a slightly inferior check.
if (isPrepared() || (!shouldPrepare() && ((QueryByExampleMechanism)getQueryMechanism()).isParsed())) {
((QueryByExampleMechanism)getQueryMechanism()).setIsParsed(false);
setSelectionCriteria(null);
}
}
if (newExampleObject != null) {
setReferenceClass(newExampleObject.getClass());
}
}
/**
* PUBLIC:
* Set the InMemoryQueryIndirectionPolicy for this query.
*/
public void setInMemoryQueryIndirectionPolicy(InMemoryQueryIndirectionPolicy inMemoryQueryIndirectionPolicy) {
// Bug2862302 Backwards compatibility. This makes sure 9.0.3 and any older version project xml don't break.
if (inMemoryQueryIndirectionPolicy != null) {
this.inMemoryQueryIndirectionPolicy = inMemoryQueryIndirectionPolicy.getPolicy();
inMemoryQueryIndirectionPolicy.setQuery(this);
}
}
/**
* PUBLIC:
* Set the InMemoryQueryIndirectionPolicy for this query.
*/
public void setInMemoryQueryIndirectionPolicyState(int inMemoryQueryIndirectionPolicy) {
this.inMemoryQueryIndirectionPolicy = inMemoryQueryIndirectionPolicy;
}
/**
* PUBLIC:
* Sets whether this is a pessimistically locking query.
* <ul>
* <li>ObjectBuildingQuery.LOCK: SELECT .... FOR UPDATE issued.
* <li>ObjectBuildingQuery.LOCK_NOWAIT: SELECT .... FOR UPDATE NO WAIT issued.
* <li>ObjectBuildingQuery.NO_LOCK: no pessimistic locking.
* <li>ObjectBuildingQuery.DEFAULT_LOCK_MODE (default) and you have a CMP descriptor:
* fine grained locking will occur.
* </ul>
* <p>Fine Grained Locking: On execution the reference class
* and those of all joined attributes will be checked. If any of these have a
* PessimisticLockingPolicy set on their descriptor, they will be locked in a
* SELECT ... FOR UPDATE OF ... {NO WAIT}. Issues fewer locks
* and avoids setting the lock mode on each query.
* <p>Example:<code>readAllQuery.setSelectionCriteria(employee.get("address").equal("Ottawa"));</code>
* <ul><li>LOCK: all employees in Ottawa and all referenced Ottawa addresses will be locked.
* <li>DEFAULT_LOCK_MODE: if address is a joined attribute, and only address has a pessimistic
* locking policy, only referenced Ottawa addresses will be locked.
* </ul>
* @see org.eclipse.persistence.descriptors.PessimisticLockingPolicy
*/
public void setLockMode(short lockMode) {
if ((lockMode == LOCK) || (lockMode == LOCK_NOWAIT)) {
lockingClause = ForUpdateClause.newInstance(lockMode);
setShouldRefreshIdentityMapResult(true);
} else if (lockMode == NO_LOCK) {
lockingClause = ForUpdateClause.newInstance(lockMode);
} else {
lockingClause = null;
setIsPrePrepared(false);
}
setIsPrepared(false);
setWasDefaultLockMode(false);
}
/**
* INTERNAL:
* returns the javax.persistence.LockModeType string value set on this query.
*/
public String getLockModeType(){
return this.lockModeType;
}
/**
* INTERNAL:
* Sets a javax.persistence.LockModeType to used with this queries execution.
* The valid types are:
* - WRITE
* - READ
* - OPTIMISTIC
* - OPTIMISTIC_FORCE_INCREMENT
* - PESSIMISTIC_READ
* - PESSIMISTIC_WRITE
* - PESSIMISTIC_FORCE_INCREMENT
* - NONE
* Setting a null type will do nothing.
* @return returns a failure flag indicating that we were UNABLE to set the
* lock mode because of validation. Callers to this method should check the
* return value and throw the necessary exception.
*/
public boolean setLockModeType(String lockModeType, AbstractSession session) {
if (lockModeType != null) {
OptimisticLockingPolicy lockingPolicy = session.getDescriptor(getReferenceClass()).getOptimisticLockingPolicy();
if (lockingPolicy == null || !(lockingPolicy instanceof VersionLockingPolicy)) {
if (! lockModeType.equals(PESSIMISTIC_READ) && ! lockModeType.equals(PESSIMISTIC_WRITE) && ! lockModeType.equals(NONE)) {
// Any locking mode other than PESSIMISTIC and NONE needs a
// version locking policy to be present, otherwise return a
// failure flag of true.
return true;
}
}
this.lockModeType = lockModeType;
setIsPrePrepared(false);
setIsPrepared(false);
setWasDefaultLockMode(false);
}
return false;
}
/**
* INTERNAL:
* Return the attributes that must be joined, but not fetched, that is,
* do not trigger the value holder.
*/
public void setNonFetchJoinAttributeExpressions(List<Expression> nonFetchJoinExpressions) {
this.nonFetchJoinAttributeExpressions = nonFetchJoinExpressions;
}
/**
* INTERNAL:
* The locking clause contains a list of expressions representing which
* objects are to be locked by the query.
* <p>
* Use for even finer grained control over what is and is not locked by
* a particular query.
*/
public void setLockingClause(ForUpdateClause clause) {
if (clause.isForUpdateOfClause()) {
this.lockingClause = clause;
setIsPrePrepared(false);
} else {
setLockMode(clause.getLockMode());
}
setWasDefaultLockMode(false);
}
/**
* INTERNAL:
* Set the partial attributes to select.
*/
public void setPartialAttributeExpressions(List<Expression> partialAttributeExpressions) {
this.partialAttributeExpressions = partialAttributeExpressions;
}
public void setEJBQLString(String ejbqlString) {
super.setEJBQLString(ejbqlString);
setIsPrePrepared(false);
}
/**
* PUBLIC:
* The QueryByExamplePolicy, is a useful to customize the query when Query By Example is used.
* The policy will control what attributes should, or should not be included in the query.
* When dealing with nulls, using special operations (notEqual, lessThan, like, etc.)
* for comparison, or choosing to include certain attributes at all times, it is useful to modify
* the policy accordingly.
* <p>Once a query is executed you must make an explicit call to setQueryByExamplePolicy
* when changing the policy, so the query will know to prepare itself again.
* <p>There is a caution to setting both a selection criteria and an example object:
* If you set the policy after execution you must also reset the selection criteria.
* (This is because after execution the original criteria and Query By Example criteria are fused together,
* and the former cannot be easily recovered).
*/
public void setQueryByExamplePolicy(QueryByExamplePolicy queryByExamplePolicy) {
if (!getQueryMechanism().isQueryByExampleMechanism()) {
setQueryMechanism(new QueryByExampleMechanism(this, getSelectionCriteria()));
((QueryByExampleMechanism)getQueryMechanism()).setQueryByExamplePolicy(queryByExamplePolicy);
setIsPrepared(false);
} else {
((QueryByExampleMechanism)getQueryMechanism()).setQueryByExamplePolicy(queryByExamplePolicy);
// Must allow the query to be prepared again.
if (isPrepared() || (!shouldPrepare() && ((QueryByExampleMechanism)getQueryMechanism()).isParsed())) {
((QueryByExampleMechanism)getQueryMechanism()).setIsParsed(false);
setSelectionCriteria(null);
// setIsPrepared(false) triggered by previous.
}
}
setIsPrePrepared(false);
}
/**
* REQUIRED:
* Set the reference class for the query.
*/
@Override
public void setReferenceClass(Class aClass) {
if (referenceClass != aClass) {
setIsPreparedKeepingSubclassData(false);
}
referenceClass = aClass;
}
/**
* INTERNAL:
* Set the reference class for the query.
*/
@Override
public void setReferenceClassName(String aClass) {
if (this.referenceClassName != aClass) {
setIsPreparedKeepingSubclassData(false);
}
this.referenceClassName = aClass;
}
/**
* PUBLIC:
* Set the Expression/where clause of the query.
* The expression should be defined using the query's ExpressionBuilder.
*/
@Override
public void setSelectionCriteria(Expression expression) {
super.setSelectionCriteria(expression);
if ((expression != null) && (this.defaultBuilder != null) && (this.defaultBuilder.getQueryClass() == null)){
// For flashback: Must make sure expression and defaultBuilder always in sync.
ExpressionBuilder newBuilder = expression.getBuilder();
if (newBuilder != this.defaultBuilder) {
if (hasAsOfClause() && getAsOfClause().isUniversal()) {
newBuilder.asOf(this.defaultBuilder.getAsOfClause());
}
this.defaultBuilder = newBuilder;
}
}
}
/**
* INTERNAL:
* Set if the rows for the result of the query should also be returned using a complex query result.
* @see ComplexQueryResult
*/
public void setShouldIncludeData(boolean shouldIncludeData) {
this.shouldIncludeData = shouldIncludeData;
if (usesResultSetAccessOptimization() && shouldIncludeData) {
// shouldIncludeData==true requires full row(s), ResultSetAccessOptimization purpose is to (sometimes) deliver incomplete row(s). These setting can't be used together.
if (this.isResultSetAccessOptimizedQuery != null) {
this.usesResultSetAccessOptimization = null;
throw QueryException.resultSetAccessOptimizationIsNotPossible(this);
} else {
this.usesResultSetAccessOptimization = Boolean.FALSE;
}
}
}
/**
* PUBLIC:
* Return if cache should be checked.
*/
public boolean shouldCheckCacheOnly() {
return this.cacheUsage == CheckCacheOnly;
}
/**
* PUBLIC:
* Return whether the descriptor's disableCacheHits setting should be checked prior
* to querying the cache.
*/
public boolean shouldCheckDescriptorForCacheUsage() {
return this.cacheUsage == UseDescriptorSetting;
}
/**
* PUBLIC:
* Should the results will be checked against the changes within the unit of work and object no longer matching or deleted will be remove, matching new objects will also be added..
*/
public boolean shouldConformResultsInUnitOfWork() {
return this.cacheUsage == ConformResultsInUnitOfWork;
}
/**
* INTERNAL:
* return true if this query should use a distinct
*/
public boolean shouldDistinctBeUsed() {
return getDistinctState() == USE_DISTINCT;
}
/**
* INTERNAL:
* Return if the rows for the result of the query should also be returned using a complex query result.
* @see ComplexQueryResult
*/
public boolean shouldIncludeData() {
return shouldIncludeData;
}
/**
* PUBLIC:
* Return if an outer join should be used to read subclasses.
* By default a separate query is done for each subclass when querying for
* a root or branch inheritance class that has subclasses that span multiple tables.
*/
public boolean shouldOuterJoinSubclasses() {
if (shouldOuterJoinSubclasses == null) {
return false;
}
return shouldOuterJoinSubclasses.booleanValue();
}
/**
* PUBLIC:
* Set if an outer join should be used to read subclasses.
* By default a separate query is done for each subclass when querying for
* a root or branch inheritance class that has subclasses that span multiple tables.
*/
public void setShouldOuterJoinSubclasses(boolean shouldOuterJoinSubclasses) {
this.shouldOuterJoinSubclasses = Boolean.valueOf(shouldOuterJoinSubclasses);
setIsPrepared(false);
}
/**
* INTERNAL:
* Return if this is a full object query, not partial nor fetch group.
*/
public boolean shouldReadAllMappings() {
return (!hasPartialAttributeExpressions()) && (this.fetchGroup == null);
}
/**
* INTERNAL:
* Check if the mapping is part of the partial attributes.
*/
public boolean shouldReadMapping(DatabaseMapping mapping, FetchGroup fetchGroup) {
String attrName = mapping.getAttributeName();
// bug 3659145 TODO - What is this bug ref? dclarke modified this next
// if block
if(fetchGroup != null) {
return fetchGroup.containsAttributeInternal(mapping.getAttributeName());
}
return isPartialAttribute(attrName);
}
/**
* ADVANCED:
* If a distinct has been set the DISTINCT clause will be printed.
* This is used internally by EclipseLink for batch reading but may also be
* used directly for advanced queries or report queries.
*/
public void useDistinct() {
setDistinctState(USE_DISTINCT);
}
/**
* INTERNAL:
* Indicates whether the query is cached as an expression query in descriptor's query manager.
*/
public boolean isCachedExpressionQuery() {
return this.isCachedExpressionQuery;
}
/**
* INTERNAL:
* Helper method that checks if clone has been locked with uow.
*/
public boolean isClonePessimisticLocked(Object clone, UnitOfWorkImpl uow) {
return this.descriptor.hasPessimisticLockingPolicy() && uow.isPessimisticLocked(clone);
}
/**
* INTERNAL:
* Cache the locking policy isReferenceClassLocked check.
*/
protected boolean isReferenceClassLocked() {
if (isReferenceClassLocked == null) {
isReferenceClassLocked = Boolean.valueOf(isLockQuery() && lockingClause.isReferenceClassLocked());
}
return isReferenceClassLocked.booleanValue();
}
/**
* INTERNAL:
* Helper method that records clone with uow if query is pessimistic locking.
*/
public void recordCloneForPessimisticLocking(Object clone, UnitOfWorkImpl uow) {
if (isReferenceClassLocked()) {
uow.addPessimisticLockedClone(clone);
}
}
/**
* ADVANCED:
* Return if the query should be optimized to build directly from the result set.
* This optimization follows an optimized path and can only be used for,
* singleton primary key, direct mapped, simple type, no inheritance, uow isolated objects.
*/
public boolean isResultSetOptimizedQuery() {
return this.isResultSetOptimizedQuery;
}
/**
* ADVANCED:
* Return if the query result set access should be optimized.
*/
public Boolean isResultSetAccessOptimizedQuery() {
return this.isResultSetAccessOptimizedQuery;
}
/**
* INTERNAL:
* Return if the query uses ResultSet optimization.
* Note that to be accurate it's required to be set by prepareResultSetAccessOptimization or checkResultSetAccessOptimization method.
* It's always returns the same value as this.isResultSetOptimizedQuery.booleanValue (if not null).
* Note that in this case if optimization is incompatible with other query settings then exception is thrown.
* Otherwise - if the session demand optimization and it is possible - optimizes (returns true),
* otherwise false.
*/
@Override
public boolean usesResultSetAccessOptimization() {
return this.usesResultSetAccessOptimization != null && this.usesResultSetAccessOptimization;
}
/**
* INTERNAL:
* Sets usesResultSetAccessOptimization based on isResultSetAccessOptimizedQuery, session default and
* query settings that could not be altered without re-preparing the query.
* Called when the query is prepared or in case usesResultSetAccessOptimization hasn't been set yet.
* Throws exception if isResultSetAccessOptimizedQuery==true cannot be accommodated because of a conflict with the query settings.
* In case of isResultSetAccessOptimizedQuery hasn't been set and session default conflicting with the the query settings
* the optimization is turned off.
*/
protected void prepareResultSetAccessOptimization() {
// if ResultSet optimization is used then ResultSet Access optimization is ignored.
if (this.isResultSetOptimizedQuery) {
return;
}
if (this.isResultSetAccessOptimizedQuery != null) {
this.usesResultSetAccessOptimization = this.isResultSetAccessOptimizedQuery;
if (this.usesResultSetAccessOptimization) {
if (!supportsResultSetAccessOptimizationOnPrepare() || !supportsResultSetAccessOptimizationOnExecute()) {
this.usesResultSetAccessOptimization = null;
throw QueryException.resultSetAccessOptimizationIsNotPossible(this);
}
}
} else {
if (this.session.shouldOptimizeResultSetAccess() && supportsResultSetAccessOptimizationOnPrepare() && supportsResultSetAccessOptimizationOnExecute()) {
this.usesResultSetAccessOptimization = Boolean.TRUE;
} else {
this.usesResultSetAccessOptimization = Boolean.FALSE;
}
}
}
/**
* INTERNAL:
*/
public void clearUsesResultSetAccessOptimization() {
this.usesResultSetAccessOptimization = null;
}
/**
* ADVANCED:
* Set if the query should be optimized to build directly from the result set.
* This optimization follows an optimized path and can only be used for,
* singleton primary key, direct mapped, simple type, no inheritance, uow isolated objects.
*/
public void setIsResultSetOptimizedQuery(boolean isResultSetOptimizedQuery) {
this.isResultSetOptimizedQuery = isResultSetOptimizedQuery;
}
/**
* ADVANCED:
* Set if the query should be optimized to build directly from the result set.
*/
public void setIsResultSetAccessOptimizedQuery(boolean isResultSetAccessOptimizedQuery) {
if (this.isResultSetAccessOptimizedQuery == null || this.isResultSetAccessOptimizedQuery.booleanValue() != isResultSetOptimizedQuery) {
this.isResultSetAccessOptimizedQuery = isResultSetAccessOptimizedQuery;
this.usesResultSetAccessOptimization = null;
}
}
/**
* ADVANCED:
* Clear the flag set by setIsResultSetOptimizedQuery method, allow to use default set on the session instead.
*/
public void clearIsResultSetOptimizedQuery() {
if (this.isResultSetAccessOptimizedQuery != null) {
this.isResultSetAccessOptimizedQuery = null;
this.usesResultSetAccessOptimization = null;
}
}
/**
* INTERNAL: Helper method to determine the default mode. If true and query has a pessimistic locking policy,
* locking will be configured according to the pessimistic locking policy.
*/
public boolean isDefaultLock() {
return (this.lockingClause == null) || wasDefaultLockMode();
}
/**
* INTERNAL:
* Return true if the query uses default properties.
* This is used to determine if this query is cacheable.
* i.e. does not use any properties that may conflict with another query
* with the same JPQL or selection criteria.
*/
@Override
public boolean isDefaultPropertiesQuery() {
return super.isDefaultPropertiesQuery()
&& (!this.isResultSetOptimizedQuery)
&& (this.isResultSetAccessOptimizedQuery == null || this.isResultSetAccessOptimizedQuery.equals(isResultSetAccessOptimizedQueryDefault))
&& (this.shouldUseSerializedObjectPolicy == shouldUseSerializedObjectPolicyDefault)
&& (isDefaultLock())
&& (!hasAdditionalFields())
&& (!hasPartialAttributeExpressions())
&& (!hasUnionExpressions())
&& (!hasNonFetchJoinedAttributeExpressions())
&& (this.fetchGroup == null)
&& (this.fetchGroupName == null)
&& (this.shouldUseDefaultFetchGroup);
}
/**
* INTERNAL:
* Checks to see if a builder has been set on the query.
*/
public boolean hasDefaultBuilder(){
return this.defaultBuilder != null;
}
/**
* Return if a fetch group is set in the query.
*/
public boolean hasFetchGroup() {
return this.fetchGroup != null;
}
/**
* Return the fetch group set in the query.
* If a fetch group is not explicitly set in the query, default fetch group optionally defined in the descriptor
* would be used, unless the user explicitly calls query.setShouldUseDefaultFetchGroup(false).
* Note that the returned fetchGroup may be updated during preProcess.
*/
public FetchGroup getFetchGroup() {
return this.fetchGroup;
}
/**
* Return the load group set in the query.
*/
public LoadGroup getLoadGroup() {
return this.loadGroup;
}
/**
* INTERNAL:
* Returns FetchGroup that will be applied to the query.
* Note that the returned fetchGroup may be updated during preProcess.
*/
@Override
public FetchGroup getExecutionFetchGroup() {
return this.fetchGroup;
}
/**
* INTERNAL:
* Returns FetchGroup that will be applied to the query.
* Note that the returned fetchGroup may be updated during preProcess.
*/
@Override
public FetchGroup getExecutionFetchGroup(ClassDescriptor descriptor) {
if (this.fetchGroup != null && descriptor.hasInheritance()){
return (FetchGroup) this.fetchGroup.findGroup(descriptor);
}
return this.fetchGroup;
}
/**
* INTERNAL:
* Indicates whether a FetchGroup will be applied to the query.
*/
public boolean hasExecutionFetchGroup() {
return getExecutionFetchGroup() != null;
}
/**
* Set a dynamic (use case) fetch group to the query.
*/
public void setFetchGroup(FetchGroup newFetchGroup) {
this.fetchGroup = newFetchGroup;
this.fetchGroupName = null;
setIsPrePrepared(false);
}
/**
* Set a descriptor-level pre-defined named fetch group to the query.
*/
public void setFetchGroupName(String groupName) {
//nullify the fetch group reference as one query can only has one fetch group.
this.fetchGroup = null;
this.fetchGroupName = groupName;
setIsPrePrepared(false);
}
/**
* Set a load group to the query.
*/
public void setLoadGroup(LoadGroup loadGroup) {
this.loadGroup = loadGroup;
}
/**
* Return the fetch group name set in the query.
*/
public String getFetchGroupName() {
return this.fetchGroupName;
}
/**
* Return false if the query does not use the default fetch group defined in the descriptor level.
*/
public boolean shouldUseDefaultFetchGroup() {
return this.shouldUseDefaultFetchGroup;
}
/**
* Set false if the user does not want to use the default fetch group defined in the descriptor level.
*/
public void setShouldUseDefaultFetchGroup(boolean shouldUseDefaultFetchGroup) {
this.shouldUseDefaultFetchGroup = shouldUseDefaultFetchGroup;
this.fetchGroup = null;
this.fetchGroupName = null;
// Force prepare again so executeFetchGroup is calculated
setIsPrePrepared(false);
}
/**
* INTERNAL:
* Return the cache of concrete subclass calls.
* This allow concrete subclasses calls to be prepared and cached for inheritance queries.
*/
public Map<Class, DatabaseCall> getConcreteSubclassCalls() {
if (concreteSubclassCalls == null) {
concreteSubclassCalls = new ConcurrentHashMap(8);
}
return concreteSubclassCalls;
}
/**
* INTERNAL:
* Return the cache of concrete subclass queries.
* This allow concrete subclasses calls to be prepared and cached for table per class inheritance and interface queries.
*/
public Map<Class, DatabaseQuery> getConcreteSubclassQueries() {
if (concreteSubclassQueries == null) {
concreteSubclassQueries = new ConcurrentHashMap(8);
}
return concreteSubclassQueries;
}
/**
* INTERNAL:
* Return the cache of aggregate queries.
* This allows aggregate query clones to be cached.
*/
public Map<DatabaseMapping, ObjectLevelReadQuery> getAggregateQueries() {
if (aggregateQueries == null) {
aggregateQueries = new HashMap(8);
}
return aggregateQueries;
}
/**
* INTERNAL:
* Return the aggregate query clone for the mapping.
*/
public ObjectLevelReadQuery getAggregateQuery(DatabaseMapping mapping) {
if (this.aggregateQueries == null) {
return null;
}
return this.aggregateQueries.get(mapping);
}
/**
* INTERNAL:
* Set the aggregate query clone for the mapping.
*/
public void setAggregateQuery(DatabaseMapping mapping, ObjectLevelReadQuery query) {
getAggregateQueries().put(mapping, query);
}
/**
* INTERNAL:
* Return the cache of concrete subclass joined mapping indexes.
* This allow concrete subclasses calls to be prepared and cached for inheritance queries.
*/
public Map<Class, Map<DatabaseMapping, Object>> getConcreteSubclassJoinedMappingIndexes() {
if (concreteSubclassJoinedMappingIndexes == null) {
concreteSubclassJoinedMappingIndexes = new ConcurrentHashMap(8);
}
return concreteSubclassJoinedMappingIndexes;
}
/**
* INTERNAL:
* Return if the query is known to be by primary key.
*/
public boolean isPrimaryKeyQuery() {
return false;
}
/**
* INTERNAL:
* Extends pessimistic lock scope.
*/
public void extendPessimisticLockScope() {
if(!shouldExtendPessimisticLockScope || getDescriptor() == null) {
return;
}
int size = getDescriptor().getMappings().size();
boolean isExtended = false;
boolean isFurtherExtensionRequired = false;
for(int i=0; i < size; i++) {
DatabaseMapping mapping = getDescriptor().getMappings().get(i);
if(mapping.isForeignReferenceMapping()) {
ForeignReferenceMapping frMapping = (ForeignReferenceMapping)mapping;
if(frMapping.shouldExtendPessimisticLockScope()) {
if(frMapping.shouldExtendPessimisticLockScopeInSourceQuery()) {
frMapping.extendPessimisticLockScopeInSourceQuery(this);
isExtended = true;
} else {
isFurtherExtensionRequired = true;
}
}
}
}
if(isExtended) {
useDistinct();
}
if(!isFurtherExtensionRequired) {
shouldExtendPessimisticLockScope = false;
}
}
/**
* Return the batch fetch policy for configuring batch fetching.
*/
public BatchFetchPolicy getBatchFetchPolicy() {
if (batchFetchPolicy == null) {
batchFetchPolicy = new BatchFetchPolicy();
}
return batchFetchPolicy;
}
/**
* Set the batch fetch policy for configuring batch fetching.
*/
public void setBatchFetchPolicy(BatchFetchPolicy batchFetchPolicy) {
this.batchFetchPolicy = batchFetchPolicy;
}
/**
* INTERNAL:
* Return all attributes specified for batch reading.
*/
public List<Expression> getBatchReadAttributeExpressions() {
return getBatchFetchPolicy().getAttributeExpressions();
}
/**
* INTERNAL:
* Set all attributes specified for batch reading.
*/
public void setBatchReadAttributeExpressions(List<Expression> attributeExpressions) {
if ((this.batchFetchPolicy == null) && (attributeExpressions.isEmpty())) {
return;
}
getBatchFetchPolicy().setAttributeExpressions(attributeExpressions);
}
/**
* INTERNAL:
* Return true is this query has batching
*/
public boolean hasBatchReadAttributes() {
return (this.batchFetchPolicy != null) && (this.batchFetchPolicy.hasAttributes());
}
/**
* INTERNAL:
* Return if the attribute is specified for batch reading.
*/
public boolean isAttributeBatchRead(ClassDescriptor mappingDescriptor, String attributeName) {
if (this.batchFetchPolicy == null) {
return false;
}
return this.batchFetchPolicy.isAttributeBatchRead(mappingDescriptor, attributeName);
}
/**
* INTERNAL:
* Used to optimize joining by pre-computing the nested join queries for the mappings.
*/
public void computeBatchReadMappingQueries() {
boolean initialized = false;
if (getDescriptor().getObjectBuilder().hasBatchFetchedAttributes()) {
// Only set the descriptor batched attributes if no batching has been set.
// This avoid endless recursion if a recursive relationship is batched.
// The batched mapping do not need to be processed up front,
// this is just an optimization, and needed for IN batching.
if (this.batchFetchPolicy == null) {
this.batchFetchPolicy = new BatchFetchPolicy();
if (getDescriptor().getObjectBuilder().hasInBatchFetchedAttribute()) {
this.batchFetchPolicy.setType(BatchFetchType.IN);
}
List<DatabaseMapping> batchedMappings = getDescriptor().getObjectBuilder().getBatchFetchedAttributes();
this.batchFetchPolicy.setMappingQueries(new HashMap(batchedMappings.size()));
initialized = true;
int size = batchedMappings.size();
for (int index = 0; index < size; index++) {
DatabaseMapping mapping = batchedMappings.get(index);
if ((mapping != null) && mapping.isForeignReferenceMapping()) {
// A nested query must be built to pass to the descriptor that looks like the real query execution would.
ReadQuery nestedQuery = ((ForeignReferenceMapping)mapping).prepareNestedBatchQuery(this);
// Register the nested query to be used by the mapping for all the objects.
this.batchFetchPolicy.getMappingQueries().put(mapping, nestedQuery);
}
}
this.batchFetchPolicy.setBatchedMappings(getDescriptor().getObjectBuilder().getBatchFetchedAttributes());
}
}
if (hasBatchReadAttributes()) {
List<Expression> batchReadAttributeExpressions = getBatchReadAttributeExpressions();
this.batchFetchPolicy.setAttributes(new ArrayList(batchReadAttributeExpressions.size()));
if (!initialized) {
this.batchFetchPolicy.setMappingQueries(new HashMap(batchReadAttributeExpressions.size()));
}
computeNestedQueriesForBatchReadExpressions(batchReadAttributeExpressions);
}
}
/**
* INTERNAL:
* Compute the cache batched attributes.
* Used to recompute batched attributes for nested aggregate queries.
*/
public void computeBatchReadAttributes() {
List<Expression> batchReadAttributeExpressions = getBatchReadAttributeExpressions();
this.batchFetchPolicy.setAttributes(new ArrayList(batchReadAttributeExpressions.size()));
int size = batchReadAttributeExpressions.size();
for (int index = 0; index < size; index++) {
ObjectExpression objectExpression = (ObjectExpression)batchReadAttributeExpressions.get(index);
// Expression may not have been initialized.
ExpressionBuilder builder = objectExpression.getBuilder();
if (builder.getSession() == null) {
builder.setSession(getSession().getRootSession(null));
}
if (builder.getQueryClass() == null) {
builder.setQueryClass(getReferenceClass());
}
// PERF: Cache join attribute names.
ObjectExpression baseExpression = objectExpression;
while (!baseExpression.getBaseExpression().isExpressionBuilder()) {
baseExpression = (ObjectExpression)baseExpression.getBaseExpression();
}
this.batchFetchPolicy.getAttributes().add(baseExpression.getName());
}
}
/**
* INTERNAL:
* This method is used when computing the nested queries for batch read mappings.
* It recurses computing the nested mapping queries.
*/
protected void computeNestedQueriesForBatchReadExpressions(List<Expression> batchReadExpressions) {
int size = batchReadExpressions.size();
for (int index = 0; index < size; index++) {
ObjectExpression objectExpression = (ObjectExpression)batchReadExpressions.get(index);
// Expression may not have been initialized.
ExpressionBuilder builder = objectExpression.getBuilder();
if (builder.getSession() == null) {
builder.setSession(getSession().getRootSession(null));
}
if (builder.getQueryClass() == null) {
builder.setQueryClass(getReferenceClass());
}
// PERF: Cache join attribute names.
ObjectExpression baseExpression = objectExpression;
while (!baseExpression.getBaseExpression().isExpressionBuilder()) {
baseExpression = (ObjectExpression)baseExpression.getBaseExpression();
}
this.batchFetchPolicy.getAttributes().add(baseExpression.getName());
DatabaseMapping mapping = baseExpression.getMapping();
if ((mapping != null) && mapping.isAggregateObjectMapping()) {
// Also prepare the nested aggregate queries, as aggregates do not have their own query.
baseExpression = objectExpression.getFirstNonAggregateExpressionAfterExpressionBuilder(new ArrayList(2));
mapping = baseExpression.getMapping();
}
if ((mapping != null) && mapping.isForeignReferenceMapping()) {
if (!this.batchFetchPolicy.getMappingQueries().containsKey(mapping)) {
// A nested query must be built to pass to the descriptor that looks like the real query execution would.
ReadQuery nestedQuery = ((ForeignReferenceMapping)mapping).prepareNestedBatchQuery(this);
// Register the nested query to be used by the mapping for all the objects.
this.batchFetchPolicy.getMappingQueries().put(mapping, nestedQuery);
}
}
}
}
/**
* PUBLIC:
* Specify the foreign-reference mapped attribute to be optimized in this query.
* The query will execute normally, however when any of the batched parts is accessed,
* the parts will all be read in a single query,
* this allows all of the data required for the parts to be read in a single query instead of (n) queries.
* This should be used when the application knows that it requires the part for all of the objects being read.
* This can be used for one-to-one, one-to-many, many-to-many and direct collection mappings.
*
* The use of the expression allows for nested batch reading to be expressed.
* <p>Example: query.addBatchReadAttribute("phoneNumbers")
*
* @see #addBatchReadAttribute(Expression)
* @see #setBatchFetchType(BatchFetchType)
* @see ObjectLevelReadQuery#addJoinedAttribute(String)
*/
public void addBatchReadAttribute(String attributeName) {
addBatchReadAttribute(getExpressionBuilder().get(attributeName));
}
/**
* PUBLIC:
* Specify the foreign-reference mapped attribute to be optimized in this query.
* The query will execute normally, however when any of the batched parts is accessed,
* the parts will all be read in a single query,
* this allows all of the data required for the parts to be read in a single query instead of (n) queries.
* This should be used when the application knows that it requires the part for all of the objects being read.
* This can be used for one-to-one, one-to-many, many-to-many and direct collection mappings.
*
* The use of the expression allows for nested batch reading to be expressed.
* <p>Example: query.addBatchReadAttribute(query.getExpressionBuilder().get("policies").get("claims"))
*
* @see #setBatchFetchType(BatchFetchType)
* @see ObjectLevelReadQuery#addJoinedAttribute(String)
*/
public void addBatchReadAttribute(Expression attributeExpression) {
if (! getQueryMechanism().isExpressionQueryMechanism()){
throw QueryException.batchReadingNotSupported(this);
}
getBatchReadAttributeExpressions().add(attributeExpression);
setIsPrepared(false);
}
/**
* PUBLIC:
* Set the batch fetch type for the query.
* This can be JOIN, EXISTS, or IN.
* This defines the type of batch reading to use with the query.
* The query must have defined batch read attributes to set its fetch type.
*
* @see #addBatchReadAttribute(Expression)
*/
public void setBatchFetchType(BatchFetchType type) {
getBatchFetchPolicy().setType(type);
setIsPrepared(false);
}
/**
* PUBLIC:
* Set the batch fetch size for the query.
* This is only relevant for the IN batch fetch type.
* This defines the max number of keys for the IN clause.
*
* @see #setBatchFetchType(BatchFetchType)
* @see #addBatchReadAttribute(Expression)
*/
public void setBatchFetchSize(int size) {
getBatchFetchPolicy().setSize(size);
setIsPrepared(false);
}
/**
* INTERNAL:
* Return temporary map of batched objects.
*/
public Map<Object, Object> getBatchObjects() {
return getBatchFetchPolicy().getBatchObjects();
}
/**
* INTERNAL:
* Set temporary map of batched objects.
*/
public void setBatchObjects(Map<Object, Object> batchObjects) {
getBatchFetchPolicy().setBatchObjects(batchObjects);
}
@Override
public String toString() {
String str = super.toString();
if(this.fetchGroup != null) {
str += '\n' + this.fetchGroup.toString();
} else if(this.fetchGroupName != null) {
str += '\n' + "FetchGroup(" + this.fetchGroupName + ")";
} else if(this.shouldUseDefaultFetchGroup) {
if(this.descriptor != null && this.descriptor.hasFetchGroupManager()) {
FetchGroup defaultFetchGroup = descriptor.getFetchGroupManager().getDefaultFetchGroup();
if(defaultFetchGroup != null) {
str += '\n' + "Default " + defaultFetchGroup.toString();
}
}
}
return str;
}
/**
* INTERNAL:
* Indicates whether the query can use ResultSet optimization.
* The method is called when the query is prepared,
* so it should refer only to the attributes that cannot be altered without re-preparing the query.
* If the query is a clone and the original has been already prepared
* this method will be called to set a (transient and therefore set to null) usesResultSetAccessOptimization attribute.
*/
public boolean supportsResultSetAccessOptimizationOnPrepare() {
DatabaseCall call = getCall();
return ((call != null) && call.getReturnsResultSet()) && // must return ResultSet
(!hasJoining() || !this.joinedAttributeManager.isToManyJoin()) &&
(!this.descriptor.hasInheritance() ||
!this.descriptor.getInheritancePolicy().hasClassExtractor() && // ClassExtractor requires the whole row
(shouldOuterJoinSubclasses() || !this.descriptor.getInheritancePolicy().requiresMultipleTableSubclassRead() || this.descriptor.getInheritancePolicy().hasView())) && // don't know how to handle select class type call - ResultSet optimization breaks it.
(this.batchFetchPolicy == null || !this.batchFetchPolicy.isIN()); // batchFetchPolicy.isIN() requires all rows up front - can't support it
}
/**
* INTERNAL:
* Indicates whether the query can use ResultSet optimization.
* Note that the session must be already set.
* The method is called when the query is executed,
* so it should refer only to the attributes that can be altered without re-preparing the query.
*/
public boolean supportsResultSetAccessOptimizationOnExecute() {
return !this.session.isConcurrent() && !this.shouldIncludeData; // doesn't make sense to use ResultSetAccessOptimization if the whole row is required
}
/**
* INTERNAL:
* Indicates whether the query should use SerializedObjectPolicy if descriptor has it.
*/
@Override
public boolean shouldUseSerializedObjectPolicy() {
return this.shouldUseSerializedObjectPolicy;
}
/**
* INTERNAL:
* Set a flag that indicates whether the query should use SerializedObjectPolicy if descriptor has it.
*/
public void setShouldUseSerializedObjectPolicy(boolean shouldUseSerializedObjectPolicy) {
if (this.shouldUseSerializedObjectPolicy != shouldUseSerializedObjectPolicy) {
if (shouldUseSerializedObjectPolicy && this.fetchGroup != null) {
// currently SOP is incompatible with fetch groups
return;
}
this.shouldUseSerializedObjectPolicy = shouldUseSerializedObjectPolicy;
setIsPrepared(false);
}
}
}
|