data-access.md 395.1 KB
Newer Older
M
Mao 已提交
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 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401
Data Access
==========

version 5.3.16

Table of Contents

* [1. Transaction Management](#transaction)
  * [1.1. Advantages of the Spring Framework’s Transaction Support Model](#transaction-motivation)
    * [1.1.1. Global Transactions](#transaction-global)
    * [1.1.2. Local Transactions](#transaction-local)
    * [1.1.3. Spring Framework’s Consistent Programming Model](#transaction-programming-model)

  * [1.2. Understanding the Spring Framework Transaction Abstraction](#transaction-strategies)
    * [1.2.1. Hibernate Transaction Setup](#transaction-strategies-hibernate)

  * [1.3. Synchronizing Resources with Transactions](#tx-resource-synchronization)
    * [1.3.1. High-level Synchronization Approach](#tx-resource-synchronization-high)
    * [1.3.2. Low-level Synchronization Approach](#tx-resource-synchronization-low)
    * [1.3.3. `TransactionAwareDataSourceProxy`](#tx-resource-synchronization-tadsp)

  * [1.4. Declarative Transaction Management](#transaction-declarative)
    * [1.4.1. Understanding the Spring Framework’s Declarative Transaction Implementation](#tx-decl-explained)
    * [1.4.2. Example of Declarative Transaction Implementation](#transaction-declarative-first-example)
    * [1.4.3. Rolling Back a Declarative Transaction](#transaction-declarative-rolling-back)
    * [1.4.4. Configuring Different Transactional Semantics for Different Beans](#transaction-declarative-diff-tx)
    * [1.4.5. \<tx:advice/\> Settings](#transaction-declarative-txadvice-settings)
    * [1.4.6. Using `@Transactional`](#transaction-declarative-annotations)
      * [`@Transactional` Settings](#transaction-declarative-attransactional-settings)
      * [Multiple Transaction Managers with `@Transactional`](#tx-multiple-tx-mgrs-with-attransactional)
      * [Custom Composed Annotations](#tx-custom-attributes)

    * [1.4.7. Transaction Propagation](#tx-propagation)
      * [Understanding `PROPAGATION_REQUIRED`](#tx-propagation-required)
      * [Understanding `PROPAGATION_REQUIRES_NEW`](#tx-propagation-requires_new)
      * [Understanding `PROPAGATION_NESTED`](#tx-propagation-nested)

    * [1.4.8. Advising Transactional Operations](#transaction-declarative-applying-more-than-just-tx-advice)
    * [1.4.9. Using `@Transactional` with AspectJ](#transaction-declarative-aspectj)

  * [1.5. Programmatic Transaction Management](#transaction-programmatic)
    * [1.5.1. Using the `TransactionTemplate`](#tx-prog-template)
      * [Specifying Transaction Settings](#tx-prog-template-settings)

    * [1.5.2. Using the `TransactionOperator`](#tx-prog-operator)
      * [Cancel Signals](#tx-prog-operator-cancel)
      * [Specifying Transaction Settings](#tx-prog-operator-settings)

    * [1.5.3. Using the `TransactionManager`](#transaction-programmatic-tm)
      * [Using the `PlatformTransactionManager`](#transaction-programmatic-ptm)
      * [Using the `ReactiveTransactionManager`](#transaction-programmatic-rtm)

  * [1.6. Choosing Between Programmatic and Declarative Transaction Management](#tx-decl-vs-prog)
  * [1.7. Transaction-bound Events](#transaction-event)
  * [1.8. Application server-specific integration](#transaction-application-server-integration)
    * [1.8.1. IBM WebSphere](#transaction-application-server-integration-websphere)
    * [1.8.2. Oracle WebLogic Server](#transaction-application-server-integration-weblogic)

  * [1.9. Solutions to Common Problems](#transaction-solutions-to-common-problems)
    * [1.9.1. Using the Wrong Transaction Manager for a Specific `DataSource`](#transaction-solutions-to-common-problems-wrong-ptm)

  * [1.10. Further Resources](#transaction-resources)

* [2. DAO Support](#dao)
  * [2.1. Consistent Exception Hierarchy](#dao-exceptions)
  * [2.2. Annotations Used to Configure DAO or Repository Classes](#dao-annotations)

* [3. Data Access with JDBC](#jdbc)
  * [3.1. Choosing an Approach for JDBC Database Access](#jdbc-choose-style)
  * [3.2. Package Hierarchy](#jdbc-packages)
  * [3.3. Using the JDBC Core Classes to Control Basic JDBC Processing and Error Handling](#jdbc-core)
    * [3.3.1. Using `JdbcTemplate`](#jdbc-JdbcTemplate)
      * [Querying (`SELECT`)](#jdbc-JdbcTemplate-examples-query)
      * [Updating (`INSERT`, `UPDATE`, and `DELETE`) with `JdbcTemplate`](#jdbc-JdbcTemplate-examples-update)
      * [Other `JdbcTemplate` Operations](#jdbc-JdbcTemplate-examples-other)
      * [`JdbcTemplate` Best Practices](#jdbc-JdbcTemplate-idioms)

    * [3.3.2. Using `NamedParameterJdbcTemplate`](#jdbc-NamedParameterJdbcTemplate)
    * [3.3.3. Using `SQLExceptionTranslator`](#jdbc-SQLExceptionTranslator)
    * [3.3.4. Running Statements](#jdbc-statements-executing)
    * [3.3.5. Running Queries](#jdbc-statements-querying)
    * [3.3.6. Updating the Database](#jdbc-updates)
    * [3.3.7. Retrieving Auto-generated Keys](#jdbc-auto-generated-keys)

  * [3.4. Controlling Database Connections](#jdbc-connections)
    * [3.4.1. Using `DataSource`](#jdbc-datasource)
    * [3.4.2. Using `DataSourceUtils`](#jdbc-DataSourceUtils)
    * [3.4.3. Implementing `SmartDataSource`](#jdbc-SmartDataSource)
    * [3.4.4. Extending `AbstractDataSource`](#jdbc-AbstractDataSource)
    * [3.4.5. Using `SingleConnectionDataSource`](#jdbc-SingleConnectionDataSource)
    * [3.4.6. Using `DriverManagerDataSource`](#jdbc-DriverManagerDataSource)
    * [3.4.7. Using `TransactionAwareDataSourceProxy`](#jdbc-TransactionAwareDataSourceProxy)
    * [3.4.8. Using `DataSourceTransactionManager`](#jdbc-DataSourceTransactionManager)

  * [3.5. JDBC Batch Operations](#jdbc-advanced-jdbc)
    * [3.5.1. Basic Batch Operations with `JdbcTemplate`](#jdbc-batch-classic)
    * [3.5.2. Batch Operations with a List of Objects](#jdbc-batch-list)
    * [3.5.3. Batch Operations with Multiple Batches](#jdbc-batch-multi)

  * [3.6. Simplifying JDBC Operations with the `SimpleJdbc` Classes](#jdbc-simple-jdbc)
    * [3.6.1. Inserting Data by Using `SimpleJdbcInsert`](#jdbc-simple-jdbc-insert-1)
    * [3.6.2. Retrieving Auto-generated Keys by Using `SimpleJdbcInsert`](#jdbc-simple-jdbc-insert-2)
    * [3.6.3. Specifying Columns for a `SimpleJdbcInsert`](#jdbc-simple-jdbc-insert-3)
    * [3.6.4. Using `SqlParameterSource` to Provide Parameter Values](#jdbc-simple-jdbc-parameters)
    * [3.6.5. Calling a Stored Procedure with `SimpleJdbcCall`](#jdbc-simple-jdbc-call-1)
    * [3.6.6. Explicitly Declaring Parameters to Use for a `SimpleJdbcCall`](#jdbc-simple-jdbc-call-2)
    * [3.6.7. How to Define `SqlParameters`](#jdbc-params)
    * [3.6.8. Calling a Stored Function by Using `SimpleJdbcCall`](#jdbc-simple-jdbc-call-3)
    * [3.6.9. Returning a `ResultSet` or REF Cursor from a `SimpleJdbcCall`](#jdbc-simple-jdbc-call-4)

  * [3.7. Modeling JDBC Operations as Java Objects](#jdbc-object)
    * [3.7.1. Understanding `SqlQuery`](#jdbc-SqlQuery)
    * [3.7.2. Using `MappingSqlQuery`](#jdbc-MappingSqlQuery)
    * [3.7.3. Using `SqlUpdate`](#jdbc-SqlUpdate)
    * [3.7.4. Using `StoredProcedure`](#jdbc-StoredProcedure)

  * [3.8. Common Problems with Parameter and Data Value Handling](#jdbc-parameter-handling)
    * [3.8.1. Providing SQL Type Information for Parameters](#jdbc-type-information)
    * [3.8.2. Handling BLOB and CLOB objects](#jdbc-lob)
    * [3.8.3. Passing in Lists of Values for IN Clause](#jdbc-in-clause)
    * [3.8.4. Handling Complex Types for Stored Procedure Calls](#jdbc-complex-types)

  * [3.9. Embedded Database Support](#jdbc-embedded-database-support)
    * [3.9.1. Why Use an Embedded Database?](#jdbc-why-embedded-database)
    * [3.9.2. Creating an Embedded Database by Using Spring XML](#jdbc-embedded-database-xml)
    * [3.9.3. Creating an Embedded Database Programmatically](#jdbc-embedded-database-java)
    * [3.9.4. Selecting the Embedded Database Type](#jdbc-embedded-database-types)
      * [Using HSQL](#jdbc-embedded-database-using-HSQL)
      * [Using H2](#jdbc-embedded-database-using-H2)
      * [Using Derby](#jdbc-embedded-database-using-Derby)

    * [3.9.5. Testing Data Access Logic with an Embedded Database](#jdbc-embedded-database-dao-testing)
    * [3.9.6. Generating Unique Names for Embedded Databases](#jdbc-embedded-database-unique-names)
    * [3.9.7. Extending the Embedded Database Support](#jdbc-embedded-database-extension)

  * [3.10. Initializing a `DataSource`](#jdbc-initializing-datasource)
    * [3.10.1. Initializing a Database by Using Spring XML](#jdbc-initializing-datasource-xml)
      * [Initialization of Other Components that Depend on the Database](#jdbc-client-component-initialization)

* [4. Data Access with R2DBC](#r2dbc)
  * [4.1. Package Hierarchy](#r2dbc-packages)
  * [4.2. Using the R2DBC Core Classes to Control Basic R2DBC Processing and Error Handling](#r2dbc-core)
    * [4.2.1. Using `DatabaseClient`](#r2dbc-DatabaseClient)
      * [Executing Statements](#r2dbc-DatabaseClient-examples-statement)
      * [Querying (`SELECT`)](#r2dbc-DatabaseClient-examples-query)
      * [Updating (`INSERT`, `UPDATE`, and `DELETE`) with `DatabaseClient`](#r2dbc-DatabaseClient-examples-update)
      * [Binding Values to Queries](#r2dbc-DatabaseClient-named-parameters)
      * [Statement Filters](#r2dbc-DatabaseClient-filter)
      * [`DatabaseClient` Best Practices](#r2dbc-DatabaseClient-idioms)

  * [4.3. Retrieving Auto-generated Keys](#r2dbc-auto-generated-keys)
  * [4.4. Controlling Database Connections](#r2dbc-connections)
    * [4.4.1. Using `ConnectionFactory`](#r2dbc-ConnectionFactory)
    * [4.4.2. Using `ConnectionFactoryUtils`](#r2dbc-ConnectionFactoryUtils)
    * [4.4.3. Using `SingleConnectionFactory`](#r2dbc-SingleConnectionFactory)
    * [4.4.4. Using `TransactionAwareConnectionFactoryProxy`](#r2dbc-TransactionAwareConnectionFactoryProxy)
    * [4.4.5. Using `R2dbcTransactionManager`](#r2dbc-R2dbcTransactionManager)

* [5. Object Relational Mapping (ORM) Data Access](#orm)
  * [5.1. Introduction to ORM with Spring](#orm-introduction)
  * [5.2. General ORM Integration Considerations](#orm-general)
    * [5.2.1. Resource and Transaction Management](#orm-resource-mngmnt)
    * [5.2.2. Exception Translation](#orm-exception-translation)

  * [5.3. Hibernate](#orm-hibernate)
    * [5.3.1. `SessionFactory` Setup in a Spring Container](#orm-session-factory-setup)
    * [5.3.2. Implementing DAOs Based on the Plain Hibernate API](#orm-hibernate-straight)
    * [5.3.3. Declarative Transaction Demarcation](#orm-hibernate-tx-declarative)
    * [5.3.4. Programmatic Transaction Demarcation](#orm-hibernate-tx-programmatic)
    * [5.3.5. Transaction Management Strategies](#orm-hibernate-tx-strategies)
    * [5.3.6. Comparing Container-managed and Locally Defined Resources](#orm-hibernate-resources)
    * [5.3.7. Spurious Application Server Warnings with Hibernate](#orm-hibernate-invalid-jdbc-access-error)

  * [5.4. JPA](#orm-jpa)
    * [5.4.1. Three Options for JPA Setup in a Spring Environment](#orm-jpa-setup)
      * [Using `LocalEntityManagerFactoryBean`](#orm-jpa-setup-lemfb)
      * [Obtaining an EntityManagerFactory from JNDI](#orm-jpa-setup-jndi)
      * [Using `LocalContainerEntityManagerFactoryBean`](#orm-jpa-setup-lcemfb)
      * [Dealing with Multiple Persistence Units](#orm-jpa-setup-multiple)
      * [Background Bootstrapping](#orm-jpa-setup-background)

    * [5.4.2. Implementing DAOs Based on JPA: `EntityManagerFactory` and `EntityManager`](#orm-jpa-dao)
    * [5.4.3. Spring-driven JPA transactions](#orm-jpa-tx)
    * [5.4.4. Understanding `JpaDialect` and `JpaVendorAdapter`](#orm-jpa-dialect)
    * [5.4.5. Setting up JPA with JTA Transaction Management](#orm-jpa-jta)
    * [5.4.6. Native Hibernate Setup and Native Hibernate Transactions for JPA Interaction](#orm-jpa-hibernate)

* [6. Marshalling XML by Using Object-XML Mappers](#oxm)
  * [6.1. Introduction](#oxm-introduction)
    * [6.1.1. Ease of configuration](#oxm-ease-of-configuration)
    * [6.1.2. Consistent Interfaces](#oxm-consistent-interfaces)
    * [6.1.3. Consistent Exception Hierarchy](#oxm-consistent-exception-hierarchy)

  * [6.2. `Marshaller` and `Unmarshaller`](#oxm-marshaller-unmarshaller)
    * [6.2.1. Understanding `Marshaller`](#oxm-marshaller)
    * [6.2.2. Understanding `Unmarshaller`](#oxm-unmarshaller)
    * [6.2.3. Understanding `XmlMappingException`](#oxm-xmlmappingexception)

  * [6.3. Using `Marshaller` and `Unmarshaller`](#oxm-usage)
  * [6.4. XML Configuration Namespace](#oxm-schema-based-config)
  * [6.5. JAXB](#oxm-jaxb)
    * [6.5.1. Using `Jaxb2Marshaller`](#oxm-jaxb2)
      * [XML Configuration Namespace](#oxm-jaxb2-xsd)

  * [6.6. JiBX](#oxm-jibx)
    * [6.6.1. Using `JibxMarshaller`](#oxm-jibx-marshaller)
      * [XML Configuration Namespace](#oxm-jibx-xsd)

  * [6.7. XStream](#oxm-xstream)
    * [6.7.1. Using `XStreamMarshaller`](#oxm-xstream-marshaller)

* [7. Appendix](#appendix)
  * [7.1. XML Schemas](#xsd-schemas)
    * [7.1.1. The `tx` Schema](#xsd-schemas-tx)
    * [7.1.2. The `jdbc` Schema](#xsd-schemas-jdbc)

This part of the reference documentation is concerned with data access and the
interaction between the data access layer and the business or service layer.

Spring’s comprehensive transaction management support is covered in some detail,
followed by thorough coverage of the various data access frameworks and technologies
with which the Spring Framework integrates.

[](#transaction)1. Transaction Management
----------

Comprehensive transaction support is among the most compelling reasons to use the Spring
Framework. The Spring Framework provides a consistent abstraction for transaction
management that delivers the following benefits:

* A consistent programming model across different transaction APIs, such as Java
  Transaction API (JTA), JDBC, Hibernate, and the Java Persistence API (JPA).

* Support for [declarative transaction management](#transaction-declarative).

* A simpler API for [programmatic](#transaction-programmatic) transaction management
  than complex transaction APIs, such as JTA.

* Excellent integration with Spring’s data access abstractions.

The following sections describe the Spring Framework’s transaction features and
technologies:

* [Advantages of the Spring Framework’s transaction support
  model](#transaction-motivation) describes why you would use the Spring Framework’s transaction abstraction
  instead of EJB Container-Managed Transactions (CMT) or choosing to drive local
  transactions through a proprietary API, such as Hibernate.

* [Understanding the Spring Framework transaction abstraction](#transaction-strategies)outlines the core classes and describes how to configure and obtain `DataSource`instances from a variety of sources.

* [Synchronizing resources with transactions](#tx-resource-synchronization) describes
  how the application code ensures that resources are created, reused, and cleaned up
  properly.

* [Declarative transaction management](#transaction-declarative) describes support for
  declarative transaction management.

* [Programmatic transaction management](#transaction-programmatic) covers support for
  programmatic (that is, explicitly coded) transaction management.

* [Transaction bound event](#transaction-event) describes how you could use application
  events within a transaction.

The chapter also includes discussions of best practices,[application server integration](#transaction-application-server-integration),
and [solutions to common problems](#transaction-solutions-to-common-problems).

### [](#transaction-motivation)1.1. Advantages of the Spring Framework’s Transaction Support Model ###

Traditionally, Java EE developers have had two choices for transaction management:
global or local transactions, both of which have profound limitations. Global
and local transaction management is reviewed in the next two sections, followed by a
discussion of how the Spring Framework’s transaction management support addresses the
limitations of the global and local transaction models.

#### [](#transaction-global)1.1.1. Global Transactions ####

Global transactions let you work with multiple transactional resources, typically
relational databases and message queues. The application server manages global
transactions through the JTA, which is a cumbersome API (partly due to its
exception model). Furthermore, a JTA `UserTransaction` normally needs to be sourced from
JNDI, meaning that you also need to use JNDI in order to use JTA. The use
of global transactions limits any potential reuse of application code, as JTA is
normally only available in an application server environment.

Previously, the preferred way to use global transactions was through EJB CMT
(Container Managed Transaction). CMT is a form of declarative transaction
management (as distinguished from programmatic transaction management). EJB CMT
removes the need for transaction-related JNDI lookups, although the use of EJB
itself necessitates the use of JNDI. It removes most but not all of the need to write
Java code to control transactions. The significant downside is that CMT is tied to JTA
and an application server environment. Also, it is only available if one chooses to
implement business logic in EJBs (or at least behind a transactional EJB facade). The
negatives of EJB in general are so great that this is not an attractive proposition,
especially in the face of compelling alternatives for declarative transaction management.

#### [](#transaction-local)1.1.2. Local Transactions ####

Local transactions are resource-specific, such as a transaction associated with a JDBC
connection. Local transactions may be easier to use but have a significant disadvantage:
They cannot work across multiple transactional resources. For example, code that manages
transactions by using a JDBC connection cannot run within a global JTA transaction. Because
the application server is not involved in transaction management, it cannot help ensure
correctness across multiple resources. (It is worth noting that most applications use a
single transaction resource.) Another downside is that local transactions are invasive
to the programming model.

#### [](#transaction-programming-model)1.1.3. Spring Framework’s Consistent Programming Model ####

Spring resolves the disadvantages of global and local transactions. It lets
application developers use a consistent programming model in any environment.
You write your code once, and it can benefit from different transaction management
strategies in different environments. The Spring Framework provides both declarative and
programmatic transaction management. Most users prefer declarative transaction
management, which we recommend in most cases.

With programmatic transaction management, developers work with the Spring Framework
transaction abstraction, which can run over any underlying transaction infrastructure.
With the preferred declarative model, developers typically write little or no code
related to transaction management and, hence, do not depend on the Spring Framework
transaction API or any other transaction API.

Do you need an application server for transaction management?

The Spring Framework’s transaction management support changes traditional rules as to
when an enterprise Java application requires an application server.

In particular, you do not need an application server purely for declarative transactions
through EJBs. In fact, even if your application server has powerful JTA capabilities,
you may decide that the Spring Framework’s declarative transactions offer more power and
a more productive programming model than EJB CMT.

Typically, you need an application server’s JTA capability only if your application needs
to handle transactions across multiple resources, which is not a requirement for many
applications. Many high-end applications use a single, highly scalable database (such as
Oracle RAC) instead. Stand-alone transaction managers (such as[Atomikos Transactions](https://www.atomikos.com/) and [JOTM](http://jotm.objectweb.org/))
are other options. Of course, you may need other application server capabilities, such as
Java Message Service (JMS) and Java EE Connector Architecture (JCA).

The Spring Framework gives you the choice of when to scale your application to a fully
loaded application server. Gone are the days when the only alternative to using EJB
CMT or JTA was to write code with local transactions (such as those on JDBC connections)
and face a hefty rework if you need that code to run within global, container-managed
transactions. With the Spring Framework, only some of the bean definitions in your
configuration file need to change (rather than your code).

### [](#transaction-strategies)1.2. Understanding the Spring Framework Transaction Abstraction ###

The key to the Spring transaction abstraction is the notion of a transaction strategy. A
transaction strategy is defined by a `TransactionManager`, specifically the`org.springframework.transaction.PlatformTransactionManager` interface for imperative
transaction management and the`org.springframework.transaction.ReactiveTransactionManager` interface for reactive
transaction management. The following listing shows the definition of the`PlatformTransactionManager` API:

```
public interface PlatformTransactionManager extends TransactionManager {

    TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException;

    void commit(TransactionStatus status) throws TransactionException;

    void rollback(TransactionStatus status) throws TransactionException;
}
```

This is primarily a service provider interface (SPI), although you can use it[programmatically](#transaction-programmatic-ptm) from your application code. Because`PlatformTransactionManager` is an interface, it can be easily mocked or stubbed as
necessary. It is not tied to a lookup strategy, such as JNDI.`PlatformTransactionManager` implementations are defined like any other object (or bean)
in the Spring Framework IoC container. This benefit alone makes Spring Framework
transactions a worthwhile abstraction, even when you work with JTA. You can test
transactional code much more easily than if it used JTA directly.

Again, in keeping with Spring’s philosophy, the `TransactionException` that can be thrown
by any of the `PlatformTransactionManager` interface’s methods is unchecked (that
is, it extends the `java.lang.RuntimeException` class). Transaction infrastructure
failures are almost invariably fatal. In rare cases where application code can actually
recover from a transaction failure, the application developer can still choose to catch
and handle `TransactionException`. The salient point is that developers are not*forced* to do so.

The `getTransaction(..)` method returns a `TransactionStatus` object, depending on a`TransactionDefinition` parameter. The returned `TransactionStatus` might represent a
new transaction or can represent an existing transaction, if a matching transaction
exists in the current call stack. The implication in this latter case is that, as with
Java EE transaction contexts, a `TransactionStatus` is associated with a thread of
execution.

As of Spring Framework 5.2, Spring also provides a transaction management abstraction for
reactive applications that make use of reactive types or Kotlin Coroutines. The following
listing shows the transaction strategy defined by`org.springframework.transaction.ReactiveTransactionManager`:

```
public interface ReactiveTransactionManager extends TransactionManager {

    Mono<ReactiveTransaction> getReactiveTransaction(TransactionDefinition definition) throws TransactionException;

    Mono<Void> commit(ReactiveTransaction status) throws TransactionException;

    Mono<Void> rollback(ReactiveTransaction status) throws TransactionException;
}
```

The reactive transaction manager is primarily a service provider interface (SPI),
although you can use it [programmatically](#transaction-programmatic-rtm) from your
application code. Because `ReactiveTransactionManager` is an interface, it can be easily
mocked or stubbed as necessary.

The `TransactionDefinition` interface specifies:

* Propagation: Typically, all code within a transaction scope runs in
  that transaction. However, you can specify the behavior if
  a transactional method is run when a transaction context already exists. For
  example, code can continue running in the existing transaction (the common case), or
  the existing transaction can be suspended and a new transaction created. Spring
  offers all of the transaction propagation options familiar from EJB CMT. To read
  about the semantics of transaction propagation in Spring, see [Transaction Propagation](#tx-propagation).

* Isolation: The degree to which this transaction is isolated from the work of other
  transactions. For example, can this transaction see uncommitted writes from other
  transactions?

* Timeout: How long this transaction runs before timing out and being automatically rolled back
  by the underlying transaction infrastructure.

* Read-only status: You can use a read-only transaction when your code reads but
  does not modify data. Read-only transactions can be a useful optimization in some
  cases, such as when you use Hibernate.

These settings reflect standard transactional concepts. If necessary, refer to resources
that discuss transaction isolation levels and other core transaction concepts.
Understanding these concepts is essential to using the Spring Framework or any
transaction management solution.

The `TransactionStatus` interface provides a simple way for transactional code to
control transaction execution and query transaction status. The concepts should be
familiar, as they are common to all transaction APIs. The following listing shows the`TransactionStatus` interface:

```
public interface TransactionStatus extends TransactionExecution, SavepointManager, Flushable {

    @Override
    boolean isNewTransaction();

    boolean hasSavepoint();

    @Override
    void setRollbackOnly();

    @Override
    boolean isRollbackOnly();

    void flush();

    @Override
    boolean isCompleted();
}
```

Regardless of whether you opt for declarative or programmatic transaction management in
Spring, defining the correct `TransactionManager` implementation is absolutely essential.
You typically define this implementation through dependency injection.

`TransactionManager` implementations normally require knowledge of the environment in
which they work: JDBC, JTA, Hibernate, and so on. The following examples show how you can
define a local `PlatformTransactionManager` implementation (in this case, with plain
JDBC.)

You can define a JDBC `DataSource` by creating a bean similar to the following:

```
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="${jdbc.driverClassName}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
</bean>
```

The related `PlatformTransactionManager` bean definition then has a reference to the`DataSource` definition. It should resemble the following example:

```
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
</bean>
```

If you use JTA in a Java EE container, then you use a container `DataSource`, obtained
through JNDI, in conjunction with Spring’s `JtaTransactionManager`. The following example
shows what the JTA and JNDI lookup version would look like:

```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/jee
        https://www.springframework.org/schema/jee/spring-jee.xsd">

    <jee:jndi-lookup id="dataSource" jndi-name="jdbc/jpetstore"/>

    <bean id="txManager" class="org.springframework.transaction.jta.JtaTransactionManager" />

    <!-- other <bean/> definitions here -->

</beans>
```

The `JtaTransactionManager` does not need to know about the `DataSource` (or any other
specific resources) because it uses the container’s global transaction management
infrastructure.

|   |The preceding definition of the `dataSource` bean uses the `<jndi-lookup/>` tag<br/>from the `jee` namespace. For more information see[The JEE Schema](integration.html#xsd-schemas-jee).|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

|   |If you use JTA, your transaction manager definition should look the same, regardless<br/>of what data access technology you use, be it JDBC, Hibernate JPA, or any other supported<br/>technology. This is due to the fact that JTA transactions are global transactions, which<br/>can enlist any transactional resource.|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

In all Spring transaction setups, application code does not need to change. You can change
how transactions are managed merely by changing configuration, even if that change means
moving from local to global transactions or vice versa.

#### [](#transaction-strategies-hibernate)1.2.1. Hibernate Transaction Setup ####

You can also easily use Hibernate local transactions, as shown in the following examples.
In this case, you need to define a Hibernate `LocalSessionFactoryBean`, which your
application code can use to obtain Hibernate `Session` instances.

The `DataSource` bean definition is similar to the local JDBC example shown previously
and, thus, is not shown in the following example.

|   |If the `DataSource` (used by any non-JTA transaction manager) is looked up through<br/>JNDI and managed by a Java EE container, it should be non-transactional, because the<br/>Spring Framework (rather than the Java EE container) manages the transactions.|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

The `txManager` bean in this case is of the `HibernateTransactionManager` type. In the
same way as the `DataSourceTransactionManager` needs a reference to the `DataSource`, the`HibernateTransactionManager` needs a reference to the `SessionFactory`. The following
example declares `sessionFactory` and `txManager` beans:

```
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="mappingResources">
        <list>
            <value>org/springframework/samples/petclinic/hibernate/petclinic.hbm.xml</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <value>
            hibernate.dialect=${hibernate.dialect}
        </value>
    </property>
</bean>

<bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory"/>
</bean>
```

If you use Hibernate and Java EE container-managed JTA transactions, you should use the
same `JtaTransactionManager` as in the previous JTA example for JDBC, as the following
example shows. Also, it is recommended to make Hibernate aware of JTA through its
transaction coordinator and possibly also its connection release mode configuration:

```
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="mappingResources">
        <list>
            <value>org/springframework/samples/petclinic/hibernate/petclinic.hbm.xml</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <value>
            hibernate.dialect=${hibernate.dialect}
            hibernate.transaction.coordinator_class=jta
            hibernate.connection.handling_mode=DELAYED_ACQUISITION_AND_RELEASE_AFTER_STATEMENT
        </value>
    </property>
</bean>

<bean id="txManager" class="org.springframework.transaction.jta.JtaTransactionManager"/>
```

Or alternatively, you may pass the `JtaTransactionManager` into your `LocalSessionFactoryBean`for enforcing the same defaults:

```
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="mappingResources">
        <list>
            <value>org/springframework/samples/petclinic/hibernate/petclinic.hbm.xml</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <value>
            hibernate.dialect=${hibernate.dialect}
        </value>
    </property>
    <property name="jtaTransactionManager" ref="txManager"/>
</bean>

<bean id="txManager" class="org.springframework.transaction.jta.JtaTransactionManager"/>
```

### [](#tx-resource-synchronization)1.3. Synchronizing Resources with Transactions ###

How to create different transaction managers and how they are linked to related resources
that need to be synchronized to transactions (for example `DataSourceTransactionManager`to a JDBC `DataSource`, `HibernateTransactionManager` to a Hibernate `SessionFactory`,
and so forth) should now be clear. This section describes how the application code
(directly or indirectly, by using a persistence API such as JDBC, Hibernate, or JPA)
ensures that these resources are created, reused, and cleaned up properly. The section
also discusses how transaction synchronization is (optionally) triggered through the
relevant `TransactionManager`.

#### [](#tx-resource-synchronization-high)1.3.1. High-level Synchronization Approach ####

The preferred approach is to use Spring’s highest-level template-based persistence
integration APIs or to use native ORM APIs with transaction-aware factory beans or
proxies for managing the native resource factories. These transaction-aware solutions
internally handle resource creation and reuse, cleanup, optional transaction
synchronization of the resources, and exception mapping. Thus, user data access code does
not have to address these tasks but can focus purely on non-boilerplate
persistence logic. Generally, you use the native ORM API or take a template approach
for JDBC access by using the `JdbcTemplate`. These solutions are detailed in subsequent
sections of this reference documentation.

#### [](#tx-resource-synchronization-low)1.3.2. Low-level Synchronization Approach ####

Classes such as `DataSourceUtils` (for JDBC), `EntityManagerFactoryUtils` (for JPA),`SessionFactoryUtils` (for Hibernate), and so on exist at a lower level. When you want the
application code to deal directly with the resource types of the native persistence APIs,
you use these classes to ensure that proper Spring Framework-managed instances are obtained,
transactions are (optionally) synchronized, and exceptions that occur in the process are
properly mapped to a consistent API.

For example, in the case of JDBC, instead of the traditional JDBC approach of calling
the `getConnection()` method on the `DataSource`, you can instead use Spring’s`org.springframework.jdbc.datasource.DataSourceUtils` class, as follows:

```
Connection conn = DataSourceUtils.getConnection(dataSource);
```

If an existing transaction already has a connection synchronized (linked) to it, that
instance is returned. Otherwise, the method call triggers the creation of a new
connection, which is (optionally) synchronized to any existing transaction and made
available for subsequent reuse in that same transaction. As mentioned earlier, any`SQLException` is wrapped in a Spring Framework `CannotGetJdbcConnectionException`, one
of the Spring Framework’s hierarchy of unchecked `DataAccessException` types. This approach
gives you more information than can be obtained easily from the `SQLException` and
ensures portability across databases and even across different persistence technologies.

This approach also works without Spring transaction management (transaction
synchronization is optional), so you can use it whether or not you use Spring for
transaction management.

Of course, once you have used Spring’s JDBC support, JPA support, or Hibernate support,
you generally prefer not to use `DataSourceUtils` or the other helper classes,
because you are much happier working through the Spring abstraction than directly
with the relevant APIs. For example, if you use the Spring `JdbcTemplate` or`jdbc.object` package to simplify your use of JDBC, correct connection retrieval occurs
behind the scenes and you need not write any special code.

#### [](#tx-resource-synchronization-tadsp)1.3.3. `TransactionAwareDataSourceProxy` ####

At the very lowest level exists the `TransactionAwareDataSourceProxy` class. This is a
proxy for a target `DataSource`, which wraps the target `DataSource` to add awareness of
Spring-managed transactions. In this respect, it is similar to a transactional JNDI`DataSource`, as provided by a Java EE server.

You should almost never need or want to use this class, except when existing
code must be called and passed a standard JDBC `DataSource` interface implementation. In
that case, it is possible that this code is usable but is participating in Spring-managed
transactions. You can write your new code by using the higher-level
abstractions mentioned earlier.

### [](#transaction-declarative)1.4. Declarative Transaction Management ###

|   |Most Spring Framework users choose declarative transaction management. This option has<br/>the least impact on application code and, hence, is most consistent with the ideals of a<br/>non-invasive lightweight container.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

The Spring Framework’s declarative transaction management is made possible with Spring
aspect-oriented programming (AOP). However, as the transactional aspects code comes
with the Spring Framework distribution and may be used in a boilerplate fashion, AOP
concepts do not generally have to be understood to make effective use of this code.

The Spring Framework’s declarative transaction management is similar to EJB CMT, in that
you can specify transaction behavior (or lack of it) down to the individual method level.
You can make a `setRollbackOnly()` call within a transaction context, if
necessary. The differences between the two types of transaction management are:

* Unlike EJB CMT, which is tied to JTA, the Spring Framework’s declarative transaction
  management works in any environment. It can work with JTA transactions or local
  transactions by using JDBC, JPA, or Hibernate by adjusting the configuration
  files.

* You can apply the Spring Framework declarative transaction management to any class,
  not merely special classes such as EJBs.

* The Spring Framework offers declarative[rollback rules](#transaction-declarative-rolling-back), a feature with no EJB
  equivalent. Both programmatic and declarative support for rollback rules is provided.

* The Spring Framework lets you customize transactional behavior by using AOP.
  For example, you can insert custom behavior in the case of transaction rollback. You
  can also add arbitrary advice, along with transactional advice. With EJB CMT, you
  cannot influence the container’s transaction management, except with`setRollbackOnly()`.

* The Spring Framework does not support propagation of transaction contexts across
  remote calls, as high-end application servers do. If you need this feature, we
  recommend that you use EJB. However, consider carefully before using such a feature,
  because, normally, one does not want transactions to span remote calls.

The concept of rollback rules is important. They let you specify which exceptions
(and throwables) should cause automatic rollback. You can specify this declaratively, in
configuration, not in Java code. So, although you can still call `setRollbackOnly()` on
the `TransactionStatus` object to roll back the current transaction back, most often you
can specify a rule that `MyApplicationException` must always result in rollback. The
significant advantage to this option is that business objects do not depend on the
transaction infrastructure. For example, they typically do not need to import Spring
transaction APIs or other Spring APIs.

Although EJB container default behavior automatically rolls back the transaction on a
system exception (usually a runtime exception), EJB CMT does not roll back the
transaction automatically on an application exception (that is, a checked exception
other than `java.rmi.RemoteException`). While the Spring default behavior for
declarative transaction management follows EJB convention (roll back is automatic only
on unchecked exceptions), it is often useful to customize this behavior.

#### [](#tx-decl-explained)1.4.1. Understanding the Spring Framework’s Declarative Transaction Implementation ####

It is not sufficient merely to tell you to annotate your classes with the`@Transactional` annotation, add `@EnableTransactionManagement` to your configuration,
and expect you to understand how it all works. To provide a deeper understanding, this
section explains the inner workings of the Spring Framework’s declarative transaction
infrastructure in the context of transaction-related issues.

The most important concepts to grasp with regard to the Spring Framework’s declarative
transaction support are that this support is enabled[via AOP proxies](core.html#aop-understanding-aop-proxies) and that the transactional
advice is driven by metadata (currently XML- or annotation-based). The combination of AOP
with transactional metadata yields an AOP proxy that uses a `TransactionInterceptor` in
conjunction with an appropriate `TransactionManager` implementation to drive transactions
around method invocations.

|   |Spring AOP is covered in [the AOP section](core.html#aop).|
|---|----------------------------------------------------------|

Spring Framework’s `TransactionInterceptor` provides transaction management for
imperative and reactive programming models. The interceptor detects the desired flavor of
transaction management by inspecting the method return type. Methods returning a reactive
type such as `Publisher` or Kotlin `Flow` (or a subtype of those) qualify for reactive
transaction management. All other return types including `void` use the code path for
imperative transaction management.

Transaction management flavors impact which transaction manager is required. Imperative
transactions require a `PlatformTransactionManager`, while reactive transactions use`ReactiveTransactionManager` implementations.

|   |`@Transactional` commonly works with thread-bound transactions managed by`PlatformTransactionManager`, exposing a transaction to all data access operations within<br/>the current execution thread. Note: This does *not* propagate to newly started threads<br/>within the method.<br/><br/>A reactive transaction managed by `ReactiveTransactionManager` uses the Reactor context<br/>instead of thread-local attributes. As a consequence, all participating data access<br/>operations need to execute within the same Reactor context in the same reactive pipeline.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

The following image shows a conceptual view of calling a method on a transactional proxy:

![tx](images/tx.png)

#### [](#transaction-declarative-first-example)1.4.2. Example of Declarative Transaction Implementation ####

Consider the following interface and its attendant implementation. This example uses`Foo` and `Bar` classes as placeholders so that you can concentrate on the transaction
usage without focusing on a particular domain model. For the purposes of this example,
the fact that the `DefaultFooService` class throws `UnsupportedOperationException`instances in the body of each implemented method is good. That behavior lets you see
transactions being created and then rolled back in response to the`UnsupportedOperationException` instance. The following listing shows the `FooService`interface:

Java

```
// the service interface that we want to make transactional

package x.y.service;

public interface FooService {

    Foo getFoo(String fooName);

    Foo getFoo(String fooName, String barName);

    void insertFoo(Foo foo);

    void updateFoo(Foo foo);

}
```

Kotlin

```
// the service interface that we want to make transactional

package x.y.service

interface FooService {

    fun getFoo(fooName: String): Foo

    fun getFoo(fooName: String, barName: String): Foo

    fun insertFoo(foo: Foo)

    fun updateFoo(foo: Foo)
}
```

The following example shows an implementation of the preceding interface:

Java

```
package x.y.service;

public class DefaultFooService implements FooService {

    @Override
    public Foo getFoo(String fooName) {
        // ...
    }

    @Override
    public Foo getFoo(String fooName, String barName) {
        // ...
    }

    @Override
    public void insertFoo(Foo foo) {
        // ...
    }

    @Override
    public void updateFoo(Foo foo) {
        // ...
    }
}
```

Kotlin

```
package x.y.service

class DefaultFooService : FooService {

    override fun getFoo(fooName: String): Foo {
        // ...
    }

    override fun getFoo(fooName: String, barName: String): Foo {
        // ...
    }

    override fun insertFoo(foo: Foo) {
        // ...
    }

    override fun updateFoo(foo: Foo) {
        // ...
    }
}
```

Assume that the first two methods of the `FooService` interface, `getFoo(String)` and`getFoo(String, String)`, must run in the context of a transaction with read-only
semantics and that the other methods, `insertFoo(Foo)` and `updateFoo(Foo)`, must
run in the context of a transaction with read-write semantics. The following
configuration is explained in detail in the next few paragraphs:

```
<!-- from the file 'context.xml' -->
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!-- this is the service object that we want to make transactional -->
    <bean id="fooService" class="x.y.service.DefaultFooService"/>

    <!-- the transactional advice (what 'happens'; see the <aop:advisor/> bean below) -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <!-- the transactional semantics... -->
        <tx:attributes>
            <!-- all methods starting with 'get' are read-only -->
            <tx:method name="get*" read-only="true"/>
            <!-- other methods use the default transaction settings (see below) -->
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>

    <!-- ensure that the above transactional advice runs for any execution
        of an operation defined by the FooService interface -->
    <aop:config>
        <aop:pointcut id="fooServiceOperation" expression="execution(* x.y.service.FooService.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="fooServiceOperation"/>
    </aop:config>

    <!-- don't forget the DataSource -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
        <property name="url" value="jdbc:oracle:thin:@rj-t42:1521:elvis"/>
        <property name="username" value="scott"/>
        <property name="password" value="tiger"/>
    </bean>

    <!-- similarly, don't forget the TransactionManager -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- other <bean/> definitions here -->

</beans>
```

Examine the preceding configuration. It assumes that you want to make a service object,
the `fooService` bean, transactional. The transaction semantics to apply are encapsulated
in the `<tx:advice/>` definition. The `<tx:advice/>` definition reads as "all methods
starting with `get` are to run in the context of a read-only transaction, and all
other methods are to run with the default transaction semantics". The`transaction-manager` attribute of the `<tx:advice/>` tag is set to the name of the`TransactionManager` bean that is going to drive the transactions (in this case, the`txManager` bean).

|   |You can omit the `transaction-manager` attribute in the transactional advice<br/>(`<tx:advice/>`) if the bean name of the `TransactionManager` that you want to<br/>wire in has the name `transactionManager`. If the `TransactionManager` bean that<br/>you want to wire in has any other name, you must use the `transaction-manager`attribute explicitly, as in the preceding example.|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

The `<aop:config/>` definition ensures that the transactional advice defined by the`txAdvice` bean runs at the appropriate points in the program. First, you define a
pointcut that matches the execution of any operation defined in the `FooService` interface
(`fooServiceOperation`). Then you associate the pointcut with the `txAdvice` by using an
advisor. The result indicates that, at the execution of a `fooServiceOperation`,
the advice defined by `txAdvice` is run.

The expression defined within the `<aop:pointcut/>` element is an AspectJ pointcut
expression. See [the AOP section](core.html#aop) for more details on pointcut
expressions in Spring.

A common requirement is to make an entire service layer transactional. The best way to
do this is to change the pointcut expression to match any operation in your
service layer. The following example shows how to do so:

```
<aop:config>
    <aop:pointcut id="fooServiceMethods" expression="execution(* x.y.service.*.*(..))"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="fooServiceMethods"/>
</aop:config>
```

|   |In the preceding example, it is assumed that all your service interfaces are defined<br/>in the `x.y.service` package. See [the AOP section](core.html#aop) for more details.|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

Now that we have analyzed the configuration, you may be asking yourself,
"What does all this configuration actually do?"

The configuration shown earlier is used to create a transactional proxy around the object
that is created from the `fooService` bean definition. The proxy is configured with
the transactional advice so that, when an appropriate method is invoked on the proxy,
a transaction is started, suspended, marked as read-only, and so on, depending on the
transaction configuration associated with that method. Consider the following program
that test drives the configuration shown earlier:

Java

```
public final class Boot {

    public static void main(final String[] args) throws Exception {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("context.xml");
        FooService fooService = ctx.getBean(FooService.class);
        fooService.insertFoo(new Foo());
    }
}
```

Kotlin

```
import org.springframework.beans.factory.getBean

fun main() {
    val ctx = ClassPathXmlApplicationContext("context.xml")
    val fooService = ctx.getBean<FooService>("fooService")
    fooService.insertFoo(Foo())
}
```

The output from running the preceding program should resemble the following (the Log4J
output and the stack trace from the `UnsupportedOperationException` thrown by the`insertFoo(..)` method of the `DefaultFooService` class have been truncated for clarity):

```
<!-- the Spring container is starting up... -->
[AspectJInvocationContextExposingAdvisorAutoProxyCreator] - Creating implicit proxy for bean 'fooService' with 0 common interceptors and 1 specific interceptors

<!-- the DefaultFooService is actually proxied -->
[JdkDynamicAopProxy] - Creating JDK dynamic proxy for [x.y.service.DefaultFooService]

<!-- ... the insertFoo(..) method is now being invoked on the proxy -->
[TransactionInterceptor] - Getting transaction for x.y.service.FooService.insertFoo

<!-- the transactional advice kicks in here... -->
[DataSourceTransactionManager] - Creating new transaction with name [x.y.service.FooService.insertFoo]
[DataSourceTransactionManager] - Acquired Connection [[email protected]] for JDBC transaction

<!-- the insertFoo(..) method from DefaultFooService throws an exception... -->
[RuleBasedTransactionAttribute] - Applying rules to determine whether transaction should rollback on java.lang.UnsupportedOperationException
[TransactionInterceptor] - Invoking rollback for transaction on x.y.service.FooService.insertFoo due to throwable [java.lang.UnsupportedOperationException]

<!-- and the transaction is rolled back (by default, RuntimeException instances cause rollback) -->
[DataSourceTransactionManager] - Rolling back JDBC transaction on Connection [[email protected]]
[DataSourceTransactionManager] - Releasing JDBC Connection after transaction
[DataSourceUtils] - Returning JDBC Connection to DataSource

Exception in thread "main" java.lang.UnsupportedOperationException at x.y.service.DefaultFooService.insertFoo(DefaultFooService.java:14)
<!-- AOP infrastructure stack trace elements removed for clarity -->
at $Proxy0.insertFoo(Unknown Source)
at Boot.main(Boot.java:11)
```

To use reactive transaction management the code has to use reactive types.

|   |Spring Framework uses the `ReactiveAdapterRegistry` to determine whether a method<br/>return type is reactive.|
|---|--------------------------------------------------------------------------------------------------------------|

The following listing shows a modified version of the previously used `FooService`, but
this time the code uses reactive types:

Java

```
// the reactive service interface that we want to make transactional

package x.y.service;

public interface FooService {

    Flux<Foo> getFoo(String fooName);

    Publisher<Foo> getFoo(String fooName, String barName);

    Mono<Void> insertFoo(Foo foo);

    Mono<Void> updateFoo(Foo foo);

}
```

Kotlin

```
// the reactive service interface that we want to make transactional

package x.y.service

interface FooService {

    fun getFoo(fooName: String): Flow<Foo>

    fun getFoo(fooName: String, barName: String): Publisher<Foo>

    fun insertFoo(foo: Foo) : Mono<Void>

    fun updateFoo(foo: Foo) : Mono<Void>
}
```

The following example shows an implementation of the preceding interface:

Java

```
package x.y.service;

public class DefaultFooService implements FooService {

    @Override
    public Flux<Foo> getFoo(String fooName) {
        // ...
    }

    @Override
    public Publisher<Foo> getFoo(String fooName, String barName) {
        // ...
    }

    @Override
    public Mono<Void> insertFoo(Foo foo) {
        // ...
    }

    @Override
    public Mono<Void> updateFoo(Foo foo) {
        // ...
    }
}
```

Kotlin

```
package x.y.service

class DefaultFooService : FooService {

    override fun getFoo(fooName: String): Flow<Foo> {
        // ...
    }

    override fun getFoo(fooName: String, barName: String): Publisher<Foo> {
        // ...
    }

    override fun insertFoo(foo: Foo): Mono<Void> {
        // ...
    }

    override fun updateFoo(foo: Foo): Mono<Void> {
        // ...
    }
}
```

Imperative and reactive transaction management share the same semantics for transaction
boundary and transaction attribute definitions. The main difference between imperative
and reactive transactions is the deferred nature of the latter. `TransactionInterceptor`decorates the returned reactive type with a transactional operator to begin and clean up
the transaction. Therefore, calling a transactional reactive method defers the actual
transaction management to a subscription type that activates processing of the reactive
type.

Another aspect of reactive transaction management relates to data escaping which is a
natural consequence of the programming model.

Method return values of imperative transactions are returned from transactional methods
upon successful termination of a method so that partially computed results do not escape
the method closure.

Reactive transaction methods return a reactive wrapper type which represents a
computation sequence along with a promise to begin and complete the computation.

A `Publisher` can emit data while a transaction is ongoing but not necessarily completed.
Therefore, methods that depend upon successful completion of an entire transaction need
to ensure completion and buffer results in the calling code.

#### [](#transaction-declarative-rolling-back)1.4.3. Rolling Back a Declarative Transaction ####

The previous section outlined the basics of how to specify transactional settings for
classes, typically service layer classes, declaratively in your application. This
section describes how you can control the rollback of transactions in a simple,
declarative fashion.

The recommended way to indicate to the Spring Framework’s transaction infrastructure
that a transaction’s work is to be rolled back is to throw an `Exception` from code that
is currently executing in the context of a transaction. The Spring Framework’s
transaction infrastructure code catches any unhandled `Exception` as it bubbles up
the call stack and makes a determination whether to mark the transaction for rollback.

In its default configuration, the Spring Framework’s transaction infrastructure code
marks a transaction for rollback only in the case of runtime, unchecked exceptions.
That is, when the thrown exception is an instance or subclass of `RuntimeException`. (`Error` instances also, by default, result in a rollback). Checked exceptions that are
thrown from a transactional method do not result in rollback in the default
configuration.

You can configure exactly which `Exception` types mark a transaction for rollback,
including checked exceptions. The following XML snippet demonstrates how you configure
rollback for a checked, application-specific `Exception` type:

```
<tx:advice id="txAdvice" transaction-manager="txManager">
    <tx:attributes>
    <tx:method name="get*" read-only="true" rollback-for="NoProductInStockException"/>
    <tx:method name="*"/>
    </tx:attributes>
</tx:advice>
```

If you do not want a transaction rolled
back when an exception is thrown, you can also specify 'no rollback rules'. The following example tells the Spring Framework’s
transaction infrastructure to commit the attendant transaction even in the face of an
unhandled `InstrumentNotFoundException`:

```
<tx:advice id="txAdvice">
    <tx:attributes>
    <tx:method name="updateStock" no-rollback-for="InstrumentNotFoundException"/>
    <tx:method name="*"/>
    </tx:attributes>
</tx:advice>
```

When the Spring Framework’s transaction infrastructure catches an exception and it
consults the configured rollback rules to determine whether to mark the transaction for
rollback, the strongest matching rule wins. So, in the case of the following
configuration, any exception other than an `InstrumentNotFoundException` results in a
rollback of the attendant transaction:

```
<tx:advice id="txAdvice">
    <tx:attributes>
    <tx:method name="*" rollback-for="Throwable" no-rollback-for="InstrumentNotFoundException"/>
    </tx:attributes>
</tx:advice>
```

You can also indicate a required rollback programmatically. Although simple,
this process is quite invasive and tightly couples your code to the Spring Framework’s
transaction infrastructure. The following example shows how to programmatically indicate
a required rollback:

Java

```
public void resolvePosition() {
    try {
        // some business logic...
    } catch (NoProductInStockException ex) {
        // trigger rollback programmatically
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    }
}
```

Kotlin

```
fun resolvePosition() {
    try {
        // some business logic...
    } catch (ex: NoProductInStockException) {
        // trigger rollback programmatically
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    }
}
```

You are strongly encouraged to use the declarative approach to rollback, if at all
possible. Programmatic rollback is available should you absolutely need it, but its
usage flies in the face of achieving a clean POJO-based architecture.

#### [](#transaction-declarative-diff-tx)1.4.4. Configuring Different Transactional Semantics for Different Beans ####

Consider the scenario where you have a number of service layer objects, and you want to
apply a totally different transactional configuration to each of them. You can do so
by defining distinct `<aop:advisor/>` elements with differing `pointcut` and`advice-ref` attribute values.

As a point of comparison, first assume that all of your service layer classes are
defined in a root `x.y.service` package. To make all beans that are instances of classes
defined in that package (or in subpackages) and that have names ending in `Service` have
the default transactional configuration, you could write the following:

```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <aop:config>

        <aop:pointcut id="serviceOperation"
                expression="execution(* x.y.service..*Service.*(..))"/>

        <aop:advisor pointcut-ref="serviceOperation" advice-ref="txAdvice"/>

    </aop:config>

    <!-- these two beans will be transactional... -->
    <bean id="fooService" class="x.y.service.DefaultFooService"/>
    <bean id="barService" class="x.y.service.extras.SimpleBarService"/>

    <!-- ... and these two beans won't -->
    <bean id="anotherService" class="org.xyz.SomeService"/> <!-- (not in the right package) -->
    <bean id="barManager" class="x.y.service.SimpleBarManager"/> <!-- (doesn't end in 'Service') -->

    <tx:advice id="txAdvice">
        <tx:attributes>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>

    <!-- other transaction infrastructure beans such as a TransactionManager omitted... -->

</beans>
```

The following example shows how to configure two distinct beans with totally different
transactional settings:

```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <aop:config>

        <aop:pointcut id="defaultServiceOperation"
                expression="execution(* x.y.service.*Service.*(..))"/>

        <aop:pointcut id="noTxServiceOperation"
                expression="execution(* x.y.service.ddl.DefaultDdlManager.*(..))"/>

        <aop:advisor pointcut-ref="defaultServiceOperation" advice-ref="defaultTxAdvice"/>

        <aop:advisor pointcut-ref="noTxServiceOperation" advice-ref="noTxAdvice"/>

    </aop:config>

    <!-- this bean will be transactional (see the 'defaultServiceOperation' pointcut) -->
    <bean id="fooService" class="x.y.service.DefaultFooService"/>

    <!-- this bean will also be transactional, but with totally different transactional settings -->
    <bean id="anotherFooService" class="x.y.service.ddl.DefaultDdlManager"/>

    <tx:advice id="defaultTxAdvice">
        <tx:attributes>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>

    <tx:advice id="noTxAdvice">
        <tx:attributes>
            <tx:method name="*" propagation="NEVER"/>
        </tx:attributes>
    </tx:advice>

    <!-- other transaction infrastructure beans such as a TransactionManager omitted... -->

</beans>
```

#### [](#transaction-declarative-txadvice-settings)1.4.5. \<tx:advice/\> Settings ####

This section summarizes the various transactional settings that you can specify by using
the `<tx:advice/>` tag. The default `<tx:advice/>` settings are:

* The [propagation setting](#tx-propagation) is `REQUIRED.`

* The isolation level is `DEFAULT.`

* The transaction is read-write.

* The transaction timeout defaults to the default timeout of the underlying transaction
  system or none if timeouts are not supported.

* Any `RuntimeException` triggers rollback, and any checked `Exception` does not.

You can change these default settings. The following table summarizes the various attributes of the `<tx:method/>` tags
that are nested within `<tx:advice/>` and `<tx:attributes/>` tags:

|    Attribute    |Required?| Default  |                                                                                                                             Description                                                                                                                              |
|-----------------|---------|----------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|     `name`      |   Yes   |          |Method names with which the transaction attributes are to be associated. The<br/>wildcard (\*) character can be used to associate the same transaction attribute<br/>settings with a number of methods (for example, `get*`, `handle*`, `on*Event`, and so<br/>forth).|
|  `propagation`  |   No    |`REQUIRED`|                                                                                                                  Transaction propagation behavior.                                                                                                                   |
|   `isolation`   |   No    |`DEFAULT` |                                                                                Transaction isolation level. Only applicable to propagation settings of `REQUIRED` or `REQUIRES_NEW`.                                                                                 |
|    `timeout`    |   No    |   \-1    |                                                                                     Transaction timeout (seconds). Only applicable to propagation `REQUIRED` or `REQUIRES_NEW`.                                                                                      |
|   `read-only`   |   No    |  false   |                                                                                        Read-write versus read-only transaction. Applies only to `REQUIRED` or `REQUIRES_NEW`.                                                                                        |
| `rollback-for`  |   No    |          |                                                                   Comma-delimited list of `Exception` instances that trigger rollback. For example,`com.foo.MyBusinessException,ServletException`.                                                                   |
|`no-rollback-for`|   No    |          |                                                               Comma-delimited list of `Exception` instances that do not trigger rollback. For example,`com.foo.MyBusinessException,ServletException`.                                                                |

#### [](#transaction-declarative-annotations)1.4.6. Using `@Transactional` ####

In addition to the XML-based declarative approach to transaction configuration, you can
use an annotation-based approach. Declaring transaction semantics directly in the Java
source code puts the declarations much closer to the affected code. There is not much
danger of undue coupling, because code that is meant to be used transactionally is
almost always deployed that way anyway.

|   |The standard `javax.transaction.Transactional` annotation is also supported as a<br/>drop-in replacement to Spring’s own annotation. Please refer to JTA 1.2 documentation<br/>for more details.|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

The ease-of-use afforded by the use of the `@Transactional` annotation is best
illustrated with an example, which is explained in the text that follows.
Consider the following class definition:

Java

```
// the service class that we want to make transactional
@Transactional
public class DefaultFooService implements FooService {

    @Override
    public Foo getFoo(String fooName) {
        // ...
    }

    @Override
    public Foo getFoo(String fooName, String barName) {
        // ...
    }

    @Override
    public void insertFoo(Foo foo) {
        // ...
    }

    @Override
    public void updateFoo(Foo foo) {
        // ...
    }
}
```

Kotlin

```
// the service class that we want to make transactional
@Transactional
class DefaultFooService : FooService {

    override fun getFoo(fooName: String): Foo {
        // ...
    }

    override fun getFoo(fooName: String, barName: String): Foo {
        // ...
    }

    override fun insertFoo(foo: Foo) {
        // ...
    }

    override fun updateFoo(foo: Foo) {
        // ...
    }
}
```

Used at the class level as above, the annotation indicates a default for all methods of
the declaring class (as well as its subclasses). Alternatively, each method can be
annotated individually. See [Method visibility and `@Transactional`](#transaction-declarative-annotations-method-visibility) for
further details on which methods Spring considers transactional. Note that a class-level
annotation does not apply to ancestor classes up the class hierarchy; in such a scenario,
inherited methods need to be locally redeclared in order to participate in a
subclass-level annotation.

When a POJO class such as the one above is defined as a bean in a Spring context,
you can make the bean instance transactional through an `@EnableTransactionManagement`annotation in a `@Configuration` class. See the[javadoc](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/transaction/annotation/EnableTransactionManagement.html)for full details.

In XML configuration, the `<tx:annotation-driven/>` tag provides similar convenience:

```
<!-- from the file 'context.xml' -->
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!-- this is the service object that we want to make transactional -->
    <bean id="fooService" class="x.y.service.DefaultFooService"/>

    <!-- enable the configuration of transactional behavior based on annotations -->
    <!-- a TransactionManager is still required -->
    <tx:annotation-driven transaction-manager="txManager"/> (1)

    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- (this dependency is defined somewhere else) -->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- other <bean/> definitions here -->

</beans>
```

|**1**|The line that makes the bean instance transactional.|
|-----|----------------------------------------------------|

|   |You can omit the `transaction-manager` attribute in the `<tx:annotation-driven/>`tag if the bean name of the `TransactionManager` that you want to wire in has the name`transactionManager`. If the `TransactionManager` bean that you want to dependency-inject<br/>has any other name, you have to use the `transaction-manager` attribute, as in the<br/>preceding example.|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

Reactive transactional methods use reactive return types in contrast to imperative
programming arrangements as the following listing shows:

Java

```
// the reactive service class that we want to make transactional
@Transactional
public class DefaultFooService implements FooService {

    @Override
    public Publisher<Foo> getFoo(String fooName) {
        // ...
    }

    @Override
    public Mono<Foo> getFoo(String fooName, String barName) {
        // ...
    }

    @Override
    public Mono<Void> insertFoo(Foo foo) {
        // ...
    }

    @Override
    public Mono<Void> updateFoo(Foo foo) {
        // ...
    }
}
```

Kotlin

```
// the reactive service class that we want to make transactional
@Transactional
class DefaultFooService : FooService {

    override fun getFoo(fooName: String): Flow<Foo> {
        // ...
    }

    override fun getFoo(fooName: String, barName: String): Mono<Foo> {
        // ...
    }

    override fun insertFoo(foo: Foo): Mono<Void> {
        // ...
    }

    override fun updateFoo(foo: Foo): Mono<Void> {
        // ...
    }
}
```

Note that there are special considerations for the returned `Publisher` with regards to
Reactive Streams cancellation signals. See the [Cancel Signals](#tx-prog-operator-cancel) section under
"Using the TransactionOperator" for more details.

|   |Method visibility and `@Transactional`<br/><br/>When you use transactional proxies with Spring’s standard configuration, you should apply<br/>the `@Transactional` annotation only to methods with `public` visibility. If you do<br/>annotate `protected`, `private`, or package-visible methods with the `@Transactional`annotation, no error is raised, but the annotated method does not exhibit the configured<br/>transactional settings. If you need to annotate non-public methods, consider the tip in<br/>the following paragraph for class-based proxies or consider using AspectJ compile-time or<br/>load-time weaving (described later).<br/><br/>When using `@EnableTransactionManagement` in a `@Configuration` class, `protected` or<br/>package-visible methods can also be made transactional for class-based proxies by<br/>registering a custom `transactionAttributeSource` bean like in the following example.<br/>Note, however, that transactional methods in interface-based proxies must always be`public` and defined in the proxied interface.<br/><br/>```<br/>/**<br/> * Register a custom AnnotationTransactionAttributeSource with the<br/> * publicMethodsOnly flag set to false to enable support for<br/> * protected and package-private @Transactional methods in<br/> * class-based proxies.<br/> *<br/> * @see ProxyTransactionManagementConfiguration#transactionAttributeSource()<br/> */<br/>@Bean<br/>TransactionAttributeSource transactionAttributeSource() {<br/>    return new AnnotationTransactionAttributeSource(false);<br/>}<br/>```<br/><br/>The *Spring TestContext Framework* supports non-private `@Transactional` test methods by<br/>default. See [Transaction Management](testing.html#testcontext-tx) in the testing<br/>chapter for examples.|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

You can apply the `@Transactional` annotation to an interface definition, a method
on an interface, a class definition, or a method on a class. However, the
mere presence of the `@Transactional` annotation is not enough to activate the
transactional behavior. The `@Transactional` annotation is merely metadata that can
be consumed by some runtime infrastructure that is `@Transactional`-aware and that
can use the metadata to configure the appropriate beans with transactional behavior.
In the preceding example, the `<tx:annotation-driven/>` element switches on the
transactional behavior.

|   |The Spring team recommends that you annotate only concrete classes (and methods of<br/>concrete classes) with the `@Transactional` annotation, as opposed to annotating interfaces.<br/>You certainly can place the `@Transactional` annotation on an interface (or an interface<br/>method), but this works only as you would expect it to if you use interface-based<br/>proxies. The fact that Java annotations are not inherited from interfaces means that,<br/>if you use class-based proxies (`proxy-target-class="true"`) or the weaving-based<br/>aspect (`mode="aspectj"`), the transaction settings are not recognized by the proxying<br/>and weaving infrastructure, and the object is not wrapped in a transactional proxy.|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

|   |In proxy mode (which is the default), only external method calls coming in through<br/>the proxy are intercepted. This means that self-invocation (in effect, a method within<br/>the target object calling another method of the target object) does not lead to an actual<br/>transaction at runtime even if the invoked method is marked with `@Transactional`. Also,<br/>the proxy must be fully initialized to provide the expected behavior, so you should not<br/>rely on this feature in your initialization code — for example, in a `@PostConstruct`method.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

Consider using AspectJ mode (see the `mode` attribute in the following table) if you
expect self-invocations to be wrapped with transactions as well. In this case, there is
no proxy in the first place. Instead, the target class is woven (that is, its byte code
is modified) to support `@Transactional` runtime behavior on any kind of method.

|    XML Attribute    |                                                                                         Annotation Attribute                                                                                         |          Default          |                                                                                                                                                                                                                                                                                                                                Description                                                                                                                                                                                                                                                                                                                                |
|---------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|`transaction-manager`|N/A (see [`TransactionManagementConfigurer`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/transaction/annotation/TransactionManagementConfigurer.html) javadoc)|   `transactionManager`    |                                                                                                                                                                                                                                                        Name of the transaction manager to use. Required only if the name of the transaction<br/>manager is not `transactionManager`, as in the preceding example.                                                                                                                                                                                                                                                         |
|       `mode`        |                                                                                                `mode`                                                                                                |          `proxy`          |The default mode (`proxy`) processes annotated beans to be proxied by using Spring’s AOP<br/>framework (following proxy semantics, as discussed earlier, applying to method calls<br/>coming in through the proxy only). The alternative mode (`aspectj`) instead weaves the<br/>affected classes with Spring’s AspectJ transaction aspect, modifying the target class<br/>byte code to apply to any kind of method call. AspectJ weaving requires`spring-aspects.jar` in the classpath as well as having load-time weaving (or compile-time<br/>weaving) enabled. (See [Spring configuration](core.html#aop-aj-ltw-spring)for details on how to set up load-time weaving.)|
|`proxy-target-class` |                                                                                          `proxyTargetClass`                                                                                          |          `false`          |                                                                                        Applies to `proxy` mode only. Controls what type of transactional proxies are created<br/>for classes annotated with the `@Transactional` annotation. If the`proxy-target-class` attribute is set to `true`, class-based proxies are created.<br/>If `proxy-target-class` is `false` or if the attribute is omitted, then standard JDK<br/>interface-based proxies are created. (See [Proxying Mechanisms](core.html#aop-proxying)for a detailed examination of the different proxy types.)                                                                                        |
|       `order`       |                                                                                               `order`                                                                                                |`Ordered.LOWEST_PRECEDENCE`|                                                                                                                                                               Defines the order of the transaction advice that is applied to beans annotated with`@Transactional`. (For more information about the rules related to ordering of AOP<br/>advice, see [Advice Ordering](core.html#aop-ataspectj-advice-ordering).)<br/>No specified ordering means that the AOP subsystem determines the order of the advice.                                                                                                                                                               |

|   |The default advice mode for processing `@Transactional` annotations is `proxy`,<br/>which allows for interception of calls through the proxy only. Local calls within the<br/>same class cannot get intercepted that way. For a more advanced mode of interception,<br/>consider switching to `aspectj` mode in combination with compile-time or load-time weaving.|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

|   |The `proxy-target-class` attribute controls what type of transactional proxies are<br/>created for classes annotated with the `@Transactional` annotation. If`proxy-target-class` is set to `true`, class-based proxies are created. If`proxy-target-class` is `false` or if the attribute is omitted, standard JDK<br/>interface-based proxies are created. (See [Proxying Mechanisms](core.html#aop-proxying)for a discussion of the different proxy types.)|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

|   |`@EnableTransactionManagement` and `<tx:annotation-driven/>` look for`@Transactional` only on beans in the same application context in which they are defined.<br/>This means that, if you put annotation-driven configuration in a `WebApplicationContext`for a `DispatcherServlet`, it checks for `@Transactional` beans only in your controllers<br/>and not in your services. See [MVC](web.html#mvc-servlet) for more information.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

The most derived location takes precedence when evaluating the transactional settings
for a method. In the case of the following example, the `DefaultFooService` class is
annotated at the class level with the settings for a read-only transaction, but the`@Transactional` annotation on the `updateFoo(Foo)` method in the same class takes
precedence over the transactional settings defined at the class level.

Java

```
@Transactional(readOnly = true)
public class DefaultFooService implements FooService {

    public Foo getFoo(String fooName) {
        // ...
    }

    // these settings have precedence for this method
    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
    public void updateFoo(Foo foo) {
        // ...
    }
}
```

Kotlin

```
@Transactional(readOnly = true)
class DefaultFooService : FooService {

    override fun getFoo(fooName: String): Foo {
        // ...
    }

    // these settings have precedence for this method
    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
    override fun updateFoo(foo: Foo) {
        // ...
    }
}
```

##### [](#transaction-declarative-attransactional-settings)`@Transactional` Settings #####

The `@Transactional` annotation is metadata that specifies that an interface, class,
or method must have transactional semantics (for example, "start a brand new read-only
transaction when this method is invoked, suspending any existing transaction").
The default `@Transactional` settings are as follows:

* The propagation setting is `PROPAGATION_REQUIRED.`

* The isolation level is `ISOLATION_DEFAULT.`

* The transaction is read-write.

* The transaction timeout defaults to the default timeout of the underlying transaction
  system, or to none if timeouts are not supported.

* Any `RuntimeException` triggers rollback, and any checked `Exception` does not.

You can change these default settings. The following table summarizes the various
properties of the `@Transactional` annotation:

|                     Property                     |                                    Type                                     |                                                         Description                                                          |
|--------------------------------------------------|-----------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------|
|[value](#tx-multiple-tx-mgrs-with-attransactional)|                                  `String`                                   |                            Optional qualifier that specifies the transaction manager to be used.                             |
|          [propagation](#tx-propagation)          |                            `enum`: `Propagation`                            |                                                Optional propagation setting.                                                 |
|                   `isolation`                    |                             `enum`: `Isolation`                             |                Optional isolation level. Applies only to propagation values of `REQUIRED` or `REQUIRES_NEW`.                 |
|                    `timeout`                     |                      `int` (in seconds of granularity)                      |              Optional transaction timeout. Applies only to propagation values of `REQUIRED` or `REQUIRES_NEW`.               |
|                    `readOnly`                    |                                  `boolean`                                  |             Read-write versus read-only transaction. Only applicable to values of `REQUIRED` or `REQUIRES_NEW`.              |
|                  `rollbackFor`                   |      Array of `Class` objects, which must be derived from `Throwable.`      |                                Optional array of exception classes that must cause rollback.                                 |
|              `rollbackForClassName`              |     Array of class names. The classes must be derived from `Throwable.`     |                            Optional array of names of exception classes that must cause rollback.                            |
|                 `noRollbackFor`                  |      Array of `Class` objects, which must be derived from `Throwable.`      |                              Optional array of exception classes that must not cause rollback.                               |
|             `noRollbackForClassName`             |   Array of `String` class names, which must be derived from `Throwable.`    |                          Optional array of names of exception classes that must not cause rollback.                          |
|                     `label`                      |Array of `String` labels to add an expressive description to the transaction.|Labels may be evaluated by transaction managers to associate<br/>implementation-specific behavior with the actual transaction.|

Currently, you cannot have explicit control over the name of a transaction, where 'name'
means the transaction name that appears in a transaction monitor, if applicable
(for example, WebLogic’s transaction monitor), and in logging output. For declarative
transactions, the transaction name is always the fully-qualified class name + `.`+ the method name of the transactionally advised class. For example, if the`handlePayment(..)` method of the `BusinessService` class started a transaction, the
name of the transaction would be: `com.example.BusinessService.handlePayment`.

##### [](#tx-multiple-tx-mgrs-with-attransactional)Multiple Transaction Managers with `@Transactional` #####

Most Spring applications need only a single transaction manager, but there may be
situations where you want multiple independent transaction managers in a single
application. You can use the `value` or `transactionManager` attribute of the`@Transactional` annotation to optionally specify the identity of the`TransactionManager` to be used. This can either be the bean name or the qualifier value
of the transaction manager bean. For example, using the qualifier notation, you can
combine the following Java code with the following transaction manager bean declarations
in the application context:

Java

```
public class TransactionalService {

    @Transactional("order")
    public void setSomething(String name) { ... }

    @Transactional("account")
    public void doSomething() { ... }

    @Transactional("reactive-account")
    public Mono<Void> doSomethingReactive() { ... }
}
```

Kotlin

```
class TransactionalService {

    @Transactional("order")
    fun setSomething(name: String) {
        // ...
    }

    @Transactional("account")
    fun doSomething() {
        // ...
    }

    @Transactional("reactive-account")
    fun doSomethingReactive(): Mono<Void> {
        // ...
    }
}
```

The following listing shows the bean declarations:

```
<tx:annotation-driven/>

    <bean id="transactionManager1" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        ...
        <qualifier value="order"/>
    </bean>

    <bean id="transactionManager2" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        ...
        <qualifier value="account"/>
    </bean>

    <bean id="transactionManager3" class="org.springframework.data.r2dbc.connectionfactory.R2dbcTransactionManager">
        ...
        <qualifier value="reactive-account"/>
    </bean>
```

In this case, the individual methods on `TransactionalService` run under separate
transaction managers, differentiated by the `order`, `account`, and `reactive-account`qualifiers. The default `<tx:annotation-driven>` target bean name, `transactionManager`,
is still used if no specifically qualified `TransactionManager` bean is found.

##### [](#tx-custom-attributes)Custom Composed Annotations #####

If you find you repeatedly use the same attributes with `@Transactional` on many different
methods, [Spring’s meta-annotation support](core.html#beans-meta-annotations) lets you
define custom composed annotations for your specific use cases. For example, consider the
following annotation definitions:

Java

```
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Transactional(transactionManager = "order", label = "causal-consistency")
public @interface OrderTx {
}

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Transactional(transactionManager = "account", label = "retryable")
public @interface AccountTx {
}
```

Kotlin

```
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.TYPE)
@Retention(AnnotationRetention.RUNTIME)
@Transactional(transactionManager = "order", label = ["causal-consistency"])
annotation class OrderTx

@Target(AnnotationTarget.FUNCTION, AnnotationTarget.TYPE)
@Retention(AnnotationRetention.RUNTIME)
@Transactional(transactionManager = "account", label = ["retryable"])
annotation class AccountTx
```

The preceding annotations let us write the example from the previous section as follows:

Java

```
public class TransactionalService {

    @OrderTx
    public void setSomething(String name) {
        // ...
    }

    @AccountTx
    public void doSomething() {
        // ...
    }
}
```

Kotlin

```
class TransactionalService {

    @OrderTx
    fun setSomething(name: String) {
        // ...
    }

    @AccountTx
    fun doSomething() {
        // ...
    }
}
```

In the preceding example, we used the syntax to define the transaction manager qualifier
and transactional labels, but we could also have included propagation behavior,
rollback rules, timeouts, and other features.

#### [](#tx-propagation)1.4.7. Transaction Propagation ####

This section describes some semantics of transaction propagation in Spring. Note
that this section is not a proper introduction to transaction propagation. Rather, it
details some of the semantics regarding transaction propagation in Spring.

In Spring-managed transactions, be aware of the difference between physical and
logical transactions, and how the propagation setting applies to this difference.

##### [](#tx-propagation-required)Understanding `PROPAGATION_REQUIRED` #####

![tx prop required](images/tx_prop_required.png)

`PROPAGATION_REQUIRED` enforces a physical transaction, either locally for the current
scope if no transaction exists yet or participating in an existing 'outer' transaction
defined for a larger scope. This is a fine default in common call stack arrangements
within the same thread (for example, a service facade that delegates to several repository methods
where all the underlying resources have to participate in the service-level transaction).

|   |By default, a participating transaction joins the characteristics of the outer scope,<br/>silently ignoring the local isolation level, timeout value, or read-only flag (if any).<br/>Consider switching the `validateExistingTransactions` flag to `true` on your transaction<br/>manager if you want isolation level declarations to be rejected when participating in<br/>an existing transaction with a different isolation level. This non-lenient mode also<br/>rejects read-only mismatches (that is, an inner read-write transaction that tries to participate<br/>in a read-only outer scope).|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

When the propagation setting is `PROPAGATION_REQUIRED`, a logical transaction scope
is created for each method upon which the setting is applied. Each such logical
transaction scope can determine rollback-only status individually, with an outer
transaction scope being logically independent from the inner transaction scope.
In the case of standard `PROPAGATION_REQUIRED` behavior, all these scopes are
mapped to the same physical transaction. So a rollback-only marker set in the inner
transaction scope does affect the outer transaction’s chance to actually commit.

However, in the case where an inner transaction scope sets the rollback-only marker, the
outer transaction has not decided on the rollback itself, so the rollback (silently
triggered by the inner transaction scope) is unexpected. A corresponding`UnexpectedRollbackException` is thrown at that point. This is expected behavior so
that the caller of a transaction can never be misled to assume that a commit was
performed when it really was not. So, if an inner transaction (of which the outer caller
is not aware) silently marks a transaction as rollback-only, the outer caller still
calls commit. The outer caller needs to receive an `UnexpectedRollbackException` to
indicate clearly that a rollback was performed instead.

##### [](#tx-propagation-requires_new)Understanding `PROPAGATION_REQUIRES_NEW` #####

![tx prop requires new](images/tx_prop_requires_new.png)

`PROPAGATION_REQUIRES_NEW`, in contrast to `PROPAGATION_REQUIRED`, always uses an
independent physical transaction for each affected transaction scope, never
participating in an existing transaction for an outer scope. In such an arrangement,
the underlying resource transactions are different and, hence, can commit or roll back
independently, with an outer transaction not affected by an inner transaction’s rollback
status and with an inner transaction’s locks released immediately after its completion.
Such an independent inner transaction can also declare its own isolation level, timeout,
and read-only settings and not inherit an outer transaction’s characteristics.

##### [](#tx-propagation-nested)Understanding `PROPAGATION_NESTED` #####

`PROPAGATION_NESTED` uses a single physical transaction with multiple savepoints
that it can roll back to. Such partial rollbacks let an inner transaction scope
trigger a rollback for its scope, with the outer transaction being able to continue
the physical transaction despite some operations having been rolled back. This setting
is typically mapped onto JDBC savepoints, so it works only with JDBC resource
transactions. See Spring’s [`DataSourceTransactionManager`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/jdbc/datasource/DataSourceTransactionManager.html).

#### [](#transaction-declarative-applying-more-than-just-tx-advice)1.4.8. Advising Transactional Operations ####

Suppose you want to run both transactional operations and some basic profiling advice.
How do you effect this in the context of `<tx:annotation-driven/>`?

When you invoke the `updateFoo(Foo)` method, you want to see the following actions:

* The configured profiling aspect starts.

* The transactional advice runs.

* The method on the advised object runs.

* The transaction commits.

* The profiling aspect reports the exact duration of the whole transactional method invocation.

|   |This chapter is not concerned with explaining AOP in any great detail (except as it<br/>applies to transactions). See [AOP](core.html#aop) for detailed coverage of the AOP<br/>configuration and AOP in general.|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

The following code shows the simple profiling aspect discussed earlier:

Java

```
package x.y;

import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.util.StopWatch;
import org.springframework.core.Ordered;

public class SimpleProfiler implements Ordered {

    private int order;

    // allows us to control the ordering of advice
    public int getOrder() {
        return this.order;
    }

    public void setOrder(int order) {
        this.order = order;
    }

    // this method is the around advice
    public Object profile(ProceedingJoinPoint call) throws Throwable {
        Object returnValue;
        StopWatch clock = new StopWatch(getClass().getName());
        try {
            clock.start(call.toShortString());
            returnValue = call.proceed();
        } finally {
            clock.stop();
            System.out.println(clock.prettyPrint());
        }
        return returnValue;
    }
}
```

Kotlin

```
class SimpleProfiler : Ordered {

    private var order: Int = 0

    // allows us to control the ordering of advice
    override fun getOrder(): Int {
        return this.order
    }

    fun setOrder(order: Int) {
        this.order = order
    }

    // this method is the around advice
    fun profile(call: ProceedingJoinPoint): Any {
        var returnValue: Any
        val clock = StopWatch(javaClass.name)
        try {
            clock.start(call.toShortString())
            returnValue = call.proceed()
        } finally {
            clock.stop()
            println(clock.prettyPrint())
        }
        return returnValue
    }
}
```

The ordering of advice
is controlled through the `Ordered` interface. For full details on advice ordering, see[Advice ordering](core.html#aop-ataspectj-advice-ordering).

The following configuration creates a `fooService` bean that has profiling and
transactional aspects applied to it in the desired order:

```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="fooService" class="x.y.service.DefaultFooService"/>

    <!-- this is the aspect -->
    <bean id="profiler" class="x.y.SimpleProfiler">
        <!-- run before the transactional advice (hence the lower order number) -->
        <property name="order" value="1"/>
    </bean>

    <tx:annotation-driven transaction-manager="txManager" order="200"/>

    <aop:config>
            <!-- this advice runs around the transactional advice -->
            <aop:aspect id="profilingAspect" ref="profiler">
                <aop:pointcut id="serviceMethodWithReturnValue"
                        expression="execution(!void x.y..*Service.*(..))"/>
                <aop:around method="profile" pointcut-ref="serviceMethodWithReturnValue"/>
            </aop:aspect>
    </aop:config>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
        <property name="url" value="jdbc:oracle:thin:@rj-t42:1521:elvis"/>
        <property name="username" value="scott"/>
        <property name="password" value="tiger"/>
    </bean>

    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

</beans>
```

You can configure any number
of additional aspects in similar fashion.

The following example creates the same setup as the previous two examples but uses the purely XML
declarative approach:

```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="fooService" class="x.y.service.DefaultFooService"/>

    <!-- the profiling advice -->
    <bean id="profiler" class="x.y.SimpleProfiler">
        <!-- run before the transactional advice (hence the lower order number) -->
        <property name="order" value="1"/>
    </bean>

    <aop:config>
        <aop:pointcut id="entryPointMethod" expression="execution(* x.y..*Service.*(..))"/>
        <!-- runs after the profiling advice (cf. the order attribute) -->

        <aop:advisor advice-ref="txAdvice" pointcut-ref="entryPointMethod" order="2"/>
        <!-- order value is higher than the profiling aspect -->

        <aop:aspect id="profilingAspect" ref="profiler">
            <aop:pointcut id="serviceMethodWithReturnValue"
                    expression="execution(!void x.y..*Service.*(..))"/>
            <aop:around method="profile" pointcut-ref="serviceMethodWithReturnValue"/>
        </aop:aspect>

    </aop:config>

    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>

    <!-- other <bean/> definitions such as a DataSource and a TransactionManager here -->

</beans>
```

The result of the preceding configuration is a `fooService` bean that has profiling and
transactional aspects applied to it in that order. If you want the profiling advice
to run after the transactional advice on the way in and before the
transactional advice on the way out, you can swap the value of the profiling
aspect bean’s `order` property so that it is higher than the transactional advice’s
order value.

You can configure additional aspects in similar fashion.

#### [](#transaction-declarative-aspectj)1.4.9. Using `@Transactional` with AspectJ ####

You can also use the Spring Framework’s `@Transactional` support outside of a Spring
container by means of an AspectJ aspect. To do so, first annotate your classes
(and optionally your classes' methods) with the `@Transactional` annotation,
and then link (weave) your application with the`org.springframework.transaction.aspectj.AnnotationTransactionAspect` defined in the`spring-aspects.jar` file. You must also configure the aspect with a transaction
manager. You can use the Spring Framework’s IoC container to take care of
dependency-injecting the aspect. The simplest way to configure the transaction
management aspect is to use the `<tx:annotation-driven/>` element and specify the `mode`attribute to `aspectj` as described in [Using `@Transactional`](#transaction-declarative-annotations). Because
we focus here on applications that run outside of a Spring container, we show
you how to do it programmatically.

|   |Prior to continuing, you may want to read [Using `@Transactional`](#transaction-declarative-annotations) and[AOP](core.html#aop) respectively.|
|---|----------------------------------------------------------------------------------------------------------------------------------------------|

The following example shows how to create a transaction manager and configure the`AnnotationTransactionAspect` to use it:

Java

```
// construct an appropriate transaction manager
DataSourceTransactionManager txManager = new DataSourceTransactionManager(getDataSource());

// configure the AnnotationTransactionAspect to use it; this must be done before executing any transactional methods
AnnotationTransactionAspect.aspectOf().setTransactionManager(txManager);
```

Kotlin

```
// construct an appropriate transaction manager
val txManager = DataSourceTransactionManager(getDataSource())

// configure the AnnotationTransactionAspect to use it; this must be done before executing any transactional methods
AnnotationTransactionAspect.aspectOf().transactionManager = txManager
```

|   |When you use this aspect, you must annotate the implementation class (or the methods<br/>within that class or both), not the interface (if any) that the class implements. AspectJ<br/>follows Java’s rule that annotations on interfaces are not inherited.|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

The `@Transactional` annotation on a class specifies the default transaction semantics
for the execution of any public method in the class.

The `@Transactional` annotation on a method within the class overrides the default
transaction semantics given by the class annotation (if present). You can annotate any method,
regardless of visibility.

To weave your applications with the `AnnotationTransactionAspect`, you must either build
your application with AspectJ (see the[AspectJ Development
Guide](https://www.eclipse.org/aspectj/doc/released/devguide/index.html)) or use load-time weaving. See [Load-time weaving with
AspectJ in the Spring Framework](core.html#aop-aj-ltw) for a discussion of load-time weaving with AspectJ.

### [](#transaction-programmatic)1.5. Programmatic Transaction Management ###

The Spring Framework provides two means of programmatic transaction management, by using:

* The `TransactionTemplate` or `TransactionalOperator`.

* A `TransactionManager` implementation directly.

The Spring team generally recommends the `TransactionTemplate` for programmatic
transaction management in imperative flows and `TransactionalOperator` for reactive code.
The second approach is similar to using the JTA `UserTransaction` API, although exception
handling is less cumbersome.

#### [](#tx-prog-template)1.5.1. Using the `TransactionTemplate` ####

The `TransactionTemplate` adopts the same approach as other Spring templates, such as
the `JdbcTemplate`. It uses a callback approach (to free application code from having to
do the boilerplate acquisition and release transactional resources) and results in
code that is intention driven, in that your code focuses solely on what
you want to do.

|   |As the examples that follow show, using the `TransactionTemplate` absolutely<br/>couples you to Spring’s transaction infrastructure and APIs. Whether or not programmatic<br/>transaction management is suitable for your development needs is a decision that you<br/>have to make yourself.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

Application code that must run in a transactional context and that explicitly uses the`TransactionTemplate` resembles the next example. You, as an application
developer, can write a `TransactionCallback` implementation (typically expressed as an
anonymous inner class) that contains the code that you need to run in the context of
a transaction. You can then pass an instance of your custom `TransactionCallback` to the`execute(..)` method exposed on the `TransactionTemplate`. The following example shows how to do so:

Java

```
public class SimpleService implements Service {

    // single TransactionTemplate shared amongst all methods in this instance
    private final TransactionTemplate transactionTemplate;

    // use constructor-injection to supply the PlatformTransactionManager
    public SimpleService(PlatformTransactionManager transactionManager) {
        this.transactionTemplate = new TransactionTemplate(transactionManager);
    }

    public Object someServiceMethod() {
        return transactionTemplate.execute(new TransactionCallback() {
            // the code in this method runs in a transactional context
            public Object doInTransaction(TransactionStatus status) {
                updateOperation1();
                return resultOfUpdateOperation2();
            }
        });
    }
}
```

Kotlin

```
// use constructor-injection to supply the PlatformTransactionManager
class SimpleService(transactionManager: PlatformTransactionManager) : Service {

    // single TransactionTemplate shared amongst all methods in this instance
    private val transactionTemplate = TransactionTemplate(transactionManager)

    fun someServiceMethod() = transactionTemplate.execute<Any?> {
        updateOperation1()
        resultOfUpdateOperation2()
    }
}
```

If there is no return value, you can use the convenient `TransactionCallbackWithoutResult` class
with an anonymous class, as follows:

Java

```
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
    protected void doInTransactionWithoutResult(TransactionStatus status) {
        updateOperation1();
        updateOperation2();
    }
});
```

Kotlin

```
transactionTemplate.execute(object : TransactionCallbackWithoutResult() {
    override fun doInTransactionWithoutResult(status: TransactionStatus) {
        updateOperation1()
        updateOperation2()
    }
})
```

Code within the callback can roll the transaction back by calling the`setRollbackOnly()` method on the supplied `TransactionStatus` object, as follows:

Java

```
transactionTemplate.execute(new TransactionCallbackWithoutResult() {

    protected void doInTransactionWithoutResult(TransactionStatus status) {
        try {
            updateOperation1();
            updateOperation2();
        } catch (SomeBusinessException ex) {
            status.setRollbackOnly();
        }
    }
});
```

Kotlin

```
transactionTemplate.execute(object : TransactionCallbackWithoutResult() {

    override fun doInTransactionWithoutResult(status: TransactionStatus) {
        try {
            updateOperation1()
            updateOperation2()
        } catch (ex: SomeBusinessException) {
            status.setRollbackOnly()
        }
    }
})
```

##### [](#tx-prog-template-settings)Specifying Transaction Settings #####

You can specify transaction settings (such as the propagation mode, the isolation level,
the timeout, and so forth) on the `TransactionTemplate` either programmatically or in
configuration. By default, `TransactionTemplate` instances have the[default transactional settings](#transaction-declarative-txadvice-settings). The
following example shows the programmatic customization of the transactional settings for
a specific `TransactionTemplate:`

Java

```
public class SimpleService implements Service {

    private final TransactionTemplate transactionTemplate;

    public SimpleService(PlatformTransactionManager transactionManager) {
        this.transactionTemplate = new TransactionTemplate(transactionManager);

        // the transaction settings can be set here explicitly if so desired
        this.transactionTemplate.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED);
        this.transactionTemplate.setTimeout(30); // 30 seconds
        // and so forth...
    }
}
```

Kotlin

```
class SimpleService(transactionManager: PlatformTransactionManager) : Service {

    private val transactionTemplate = TransactionTemplate(transactionManager).apply {
        // the transaction settings can be set here explicitly if so desired
        isolationLevel = TransactionDefinition.ISOLATION_READ_UNCOMMITTED
        timeout = 30 // 30 seconds
        // and so forth...
    }
}
```

The following example defines a `TransactionTemplate` with some custom transactional
settings by using Spring XML configuration:

```
<bean id="sharedTransactionTemplate"
        class="org.springframework.transaction.support.TransactionTemplate">
    <property name="isolationLevelName" value="ISOLATION_READ_UNCOMMITTED"/>
    <property name="timeout" value="30"/>
</bean>
```

You can then inject the `sharedTransactionTemplate`into as many services as are required.

Finally, instances of the `TransactionTemplate` class are thread-safe, in that instances
do not maintain any conversational state. `TransactionTemplate` instances do, however,
maintain configuration state. So, while a number of classes may share a single instance
of a `TransactionTemplate`, if a class needs to use a `TransactionTemplate` with
different settings (for example, a different isolation level), you need to create
two distinct `TransactionTemplate` instances.

#### [](#tx-prog-operator)1.5.2. Using the `TransactionOperator` ####

The `TransactionOperator` follows an operator design that is similar to other reactive
operators. It uses a callback approach (to free application code from having to do the
boilerplate acquisition and release transactional resources) and results in code that is
intention driven, in that your code focuses solely on what you want to do.

|   |As the examples that follow show, using the `TransactionOperator` absolutely<br/>couples you to Spring’s transaction infrastructure and APIs. Whether or not programmatic<br/>transaction management is suitable for your development needs is a decision that you have<br/>to make yourself.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

Application code that must run in a transactional context and that explicitly uses
the `TransactionOperator` resembles the next example:

Java

```
public class SimpleService implements Service {

    // single TransactionOperator shared amongst all methods in this instance
    private final TransactionalOperator transactionalOperator;

    // use constructor-injection to supply the ReactiveTransactionManager
    public SimpleService(ReactiveTransactionManager transactionManager) {
        this.transactionOperator = TransactionalOperator.create(transactionManager);
    }

    public Mono<Object> someServiceMethod() {

        // the code in this method runs in a transactional context

        Mono<Object> update = updateOperation1();

        return update.then(resultOfUpdateOperation2).as(transactionalOperator::transactional);
    }
}
```

Kotlin

```
// use constructor-injection to supply the ReactiveTransactionManager
class SimpleService(transactionManager: ReactiveTransactionManager) : Service {

    // single TransactionalOperator shared amongst all methods in this instance
    private val transactionalOperator = TransactionalOperator.create(transactionManager)

    suspend fun someServiceMethod() = transactionalOperator.executeAndAwait<Any?> {
        updateOperation1()
        resultOfUpdateOperation2()
    }
}
```

`TransactionalOperator` can be used in two ways:

* Operator-style using Project Reactor types (`mono.as(transactionalOperator::transactional)`)

* Callback-style for every other case (`transactionalOperator.execute(TransactionCallback<T>)`)

Code within the callback can roll the transaction back by calling the `setRollbackOnly()`method on the supplied `ReactiveTransaction` object, as follows:

Java

```
transactionalOperator.execute(new TransactionCallback<>() {

    public Mono<Object> doInTransaction(ReactiveTransaction status) {
        return updateOperation1().then(updateOperation2)
                    .doOnError(SomeBusinessException.class, e -> status.setRollbackOnly());
        }
    }
});
```

Kotlin

```
transactionalOperator.execute(object : TransactionCallback() {

    override fun doInTransactionWithoutResult(status: ReactiveTransaction) {
        updateOperation1().then(updateOperation2)
                    .doOnError(SomeBusinessException.class, e -> status.setRollbackOnly())
    }
})
```

##### [](#tx-prog-operator-cancel)Cancel Signals #####

In Reactive Streams, a `Subscriber` can cancel its `Subscription` and stop its`Publisher`. Operators in Project Reactor, as well as in other libraries, such as `next()`,`take(long)`, `timeout(Duration)`, and others can issue cancellations. There is no way to
know the reason for the cancellation, whether it is due to an error or a simply lack of
interest to consume further. Since version 5.3 cancel signals lead to a roll back.
As a result it is important to consider the operators used downstream from a transaction`Publisher`. In particular in the case of a `Flux` or other multi-value `Publisher`,
the full output must be consumed to allow the transaction to complete.

##### [](#tx-prog-operator-settings)Specifying Transaction Settings #####

You can specify transaction settings (such as the propagation mode, the isolation level,
the timeout, and so forth) for the `TransactionalOperator`. By default,`TransactionalOperator` instances have[default transactional settings](#transaction-declarative-txadvice-settings). The
following example shows customization of the transactional settings for a specific`TransactionalOperator:`

Java

```
public class SimpleService implements Service {

    private final TransactionalOperator transactionalOperator;

    public SimpleService(ReactiveTransactionManager transactionManager) {
        DefaultTransactionDefinition definition = new DefaultTransactionDefinition();

        // the transaction settings can be set here explicitly if so desired
        definition.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED);
        definition.setTimeout(30); // 30 seconds
        // and so forth...

        this.transactionalOperator = TransactionalOperator.create(transactionManager, definition);
    }
}
```

Kotlin

```
class SimpleService(transactionManager: ReactiveTransactionManager) : Service {

    private val definition = DefaultTransactionDefinition().apply {
        // the transaction settings can be set here explicitly if so desired
        isolationLevel = TransactionDefinition.ISOLATION_READ_UNCOMMITTED
        timeout = 30 // 30 seconds
        // and so forth...
    }
    private val transactionalOperator = TransactionalOperator(transactionManager, definition)
}
```

#### [](#transaction-programmatic-tm)1.5.3. Using the `TransactionManager` ####

The following sections explain programmatic usage of imperative and reactive transaction
managers.

##### [](#transaction-programmatic-ptm)Using the `PlatformTransactionManager` #####

For imperative transactions, you can use a`org.springframework.transaction.PlatformTransactionManager` directly to manage your
transaction. To do so, pass the implementation of the `PlatformTransactionManager` you
use to your bean through a bean reference. Then, by using the `TransactionDefinition` and`TransactionStatus` objects, you can initiate transactions, roll back, and commit. The
following example shows how to do so:

Java

```
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
// explicitly setting the transaction name is something that can be done only programmatically
def.setName("SomeTxName");
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

TransactionStatus status = txManager.getTransaction(def);
try {
    // put your business logic here
} catch (MyException ex) {
    txManager.rollback(status);
    throw ex;
}
txManager.commit(status);
```

Kotlin

```
val def = DefaultTransactionDefinition()
// explicitly setting the transaction name is something that can be done only programmatically
def.setName("SomeTxName")
def.propagationBehavior = TransactionDefinition.PROPAGATION_REQUIRED

val status = txManager.getTransaction(def)
try {
    // put your business logic here
} catch (ex: MyException) {
    txManager.rollback(status)
    throw ex
}

txManager.commit(status)
```

##### [](#transaction-programmatic-rtm)Using the `ReactiveTransactionManager` #####

When working with reactive transactions, you can use a`org.springframework.transaction.ReactiveTransactionManager` directly to manage your
transaction. To do so, pass the implementation of the `ReactiveTransactionManager` you
use to your bean through a bean reference. Then, by using the `TransactionDefinition` and`ReactiveTransaction` objects, you can initiate transactions, roll back, and commit. The
following example shows how to do so:

Java

```
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
// explicitly setting the transaction name is something that can be done only programmatically
def.setName("SomeTxName");
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

Mono<ReactiveTransaction> reactiveTx = txManager.getReactiveTransaction(def);

reactiveTx.flatMap(status -> {

    Mono<Object> tx = ...; // put your business logic here

    return tx.then(txManager.commit(status))
            .onErrorResume(ex -> txManager.rollback(status).then(Mono.error(ex)));
});
```

Kotlin

```
val def = DefaultTransactionDefinition()
// explicitly setting the transaction name is something that can be done only programmatically
def.setName("SomeTxName")
def.propagationBehavior = TransactionDefinition.PROPAGATION_REQUIRED

val reactiveTx = txManager.getReactiveTransaction(def)
reactiveTx.flatMap { status ->

    val tx = ... // put your business logic here

    tx.then(txManager.commit(status))
            .onErrorResume { ex -> txManager.rollback(status).then(Mono.error(ex)) }
}
```

### [](#tx-decl-vs-prog)1.6. Choosing Between Programmatic and Declarative Transaction Management ###

Programmatic transaction management is usually a good idea only if you have a small
number of transactional operations. For example, if you have a web application that
requires transactions only for certain update operations, you may not want to set up
transactional proxies by using Spring or any other technology. In this case, using the`TransactionTemplate` may be a good approach. Being able to set the transaction name
explicitly is also something that can be done only by using the programmatic approach
to transaction management.

On the other hand, if your application has numerous transactional operations,
declarative transaction management is usually worthwhile. It keeps transaction
management out of business logic and is not difficult to configure. When using the
Spring Framework, rather than EJB CMT, the configuration cost of declarative transaction
management is greatly reduced.

### [](#transaction-event)1.7. Transaction-bound Events ###

As of Spring 4.2, the listener of an event can be bound to a phase of the transaction.
The typical example is to handle the event when the transaction has completed successfully.
Doing so lets events be used with more flexibility when the outcome of the current
transaction actually matters to the listener.

You can register a regular event listener by using the `@EventListener` annotation.
If you need to bind it to the transaction, use `@TransactionalEventListener`.
When you do so, the listener is bound to the commit phase of the transaction by default.

The next example shows this concept. Assume that a component publishes an order-created
event and that we want to define a listener that should only handle that event once the
transaction in which it has been published has committed successfully. The following
example sets up such an event listener:

Java

```
@Component
public class MyComponent {

    @TransactionalEventListener
    public void handleOrderCreatedEvent(CreationEvent<Order> creationEvent) {
        // ...
    }
}
```

Kotlin

```
@Component
class MyComponent {

    @TransactionalEventListener
    fun handleOrderCreatedEvent(creationEvent: CreationEvent<Order>) {
        // ...
    }
}
```

The `@TransactionalEventListener` annotation exposes a `phase` attribute that lets you
customize the phase of the transaction to which the listener should be bound.
The valid phases are `BEFORE_COMMIT`, `AFTER_COMMIT` (default), `AFTER_ROLLBACK`, as well as`AFTER_COMPLETION` which aggregates the transaction completion (be it a commit or a rollback).

If no transaction is running, the listener is not invoked at all, since we cannot honor the
required semantics. You can, however, override that behavior by setting the `fallbackExecution`attribute of the annotation to `true`.

|   |`@TransactionalEventListener` only works with thread-bound transactions managed by`PlatformTransactionManager`. A reactive transaction managed by `ReactiveTransactionManager`uses the Reactor context instead of thread-local attributes, so from the perspective of<br/>an event listener, there is no compatible active transaction that it can participate in.|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### [](#transaction-application-server-integration)1.8. Application server-specific integration ###

Spring’s transaction abstraction is generally application server-agnostic. Additionally,
Spring’s `JtaTransactionManager` class (which can optionally perform a JNDI lookup for
the JTA `UserTransaction` and `TransactionManager` objects) autodetects the location for
the latter object, which varies by application server. Having access to the JTA`TransactionManager` allows for enhanced transaction semantics — in particular,
supporting transaction suspension. See the[`JtaTransactionManager`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/transaction/jta/JtaTransactionManager.html)javadoc for details.

Spring’s `JtaTransactionManager` is the standard choice to run on Java EE application
servers and is known to work on all common servers. Advanced functionality, such as
transaction suspension, works on many servers as well (including GlassFish, JBoss and
Geronimo) without any special configuration required. However, for fully supported
transaction suspension and further advanced integration, Spring includes special adapters
for WebLogic Server and WebSphere. These adapters are discussed in the following
sections.

For standard scenarios, including WebLogic Server and WebSphere, consider using the
convenient `<tx:jta-transaction-manager/>` configuration element. When configured,
this element automatically detects the underlying server and chooses the best
transaction manager available for the platform. This means that you need not explicitly
configure server-specific adapter classes (as discussed in the following sections).
Rather, they are chosen automatically, with the standard`JtaTransactionManager` as the default fallback.

#### [](#transaction-application-server-integration-websphere)1.8.1. IBM WebSphere ####

On WebSphere 6.1.0.9 and above, the recommended Spring JTA transaction manager to use is`WebSphereUowTransactionManager`. This special adapter uses IBM’s `UOWManager` API,
which is available in WebSphere Application Server 6.1.0.9 and later. With this adapter,
Spring-driven transaction suspension (suspend and resume as initiated by`PROPAGATION_REQUIRES_NEW`) is officially supported by IBM.

#### [](#transaction-application-server-integration-weblogic)1.8.2. Oracle WebLogic Server ####

On WebLogic Server 9.0 or above, you would typically use the`WebLogicJtaTransactionManager` instead of the stock `JtaTransactionManager` class. This
special WebLogic-specific subclass of the normal `JtaTransactionManager` supports the
full power of Spring’s transaction definitions in a WebLogic-managed transaction
environment, beyond standard JTA semantics. Features include transaction names,
per-transaction isolation levels, and proper resuming of transactions in all cases.

### [](#transaction-solutions-to-common-problems)1.9. Solutions to Common Problems ###

This section describes solutions to some common problems.

#### [](#transaction-solutions-to-common-problems-wrong-ptm)1.9.1. Using the Wrong Transaction Manager for a Specific `DataSource` ####

Use the correct `PlatformTransactionManager` implementation based on your choice of
transactional technologies and requirements. Used properly, the Spring Framework merely
provides a straightforward and portable abstraction. If you use global
transactions, you must use the`org.springframework.transaction.jta.JtaTransactionManager` class (or an[application server-specific subclass](#transaction-application-server-integration) of
it) for all your transactional operations. Otherwise, the transaction infrastructure
tries to perform local transactions on such resources as container `DataSource`instances. Such local transactions do not make sense, and a good application server
treats them as errors.

### [](#transaction-resources)1.10. Further Resources ###

For more information about the Spring Framework’s transaction support, see:

* [Distributed
  transactions in Spring, with and without XA](https://www.javaworld.com/javaworld/jw-01-2009/jw-01-spring-transactions.html) is a JavaWorld presentation in which
  Spring’s David Syer guides you through seven patterns for distributed
  transactions in Spring applications, three of them with XA and four without.

* [*Java Transaction Design Strategies*](https://www.infoq.com/minibooks/JTDS) is a book
  available from [InfoQ](https://www.infoq.com/) that provides a well-paced introduction
  to transactions in Java. It also includes side-by-side examples of how to configure
  and use transactions with both the Spring Framework and EJB3.

[](#dao)2. DAO Support
----------

The Data Access Object (DAO) support in Spring is aimed at making it easy to work with
data access technologies (such as JDBC, Hibernate, or JPA) in a consistent way. This
lets you switch between the aforementioned persistence technologies fairly easily,
and it also lets you code without worrying about catching exceptions that are
specific to each technology.

### [](#dao-exceptions)2.1. Consistent Exception Hierarchy ###

Spring provides a convenient translation from technology-specific exceptions, such as`SQLException` to its own exception class hierarchy, which has `DataAccessException` as
the root exception. These exceptions wrap the original exception so that there is never
any risk that you might lose any information about what might have gone wrong.

In addition to JDBC exceptions, Spring can also wrap JPA- and Hibernate-specific exceptions,
converting them to a set of focused runtime exceptions. This lets you handle most
non-recoverable persistence exceptions in only the appropriate layers, without having
annoying boilerplate catch-and-throw blocks and exception declarations in your DAOs.
(You can still trap and handle exceptions anywhere you need to though.) As mentioned above,
JDBC exceptions (including database-specific dialects) are also converted to the same
hierarchy, meaning that you can perform some operations with JDBC within a consistent
programming model.

The preceding discussion holds true for the various template classes in Spring’s support
for various ORM frameworks. If you use the interceptor-based classes, the application must
care about handling `HibernateExceptions` and `PersistenceExceptions` itself, preferably by
delegating to the `convertHibernateAccessException(..)` or `convertJpaAccessException(..)`methods, respectively, of `SessionFactoryUtils`. These methods convert the exceptions
to exceptions that are compatible with the exceptions in the `org.springframework.dao`exception hierarchy. As `PersistenceExceptions` are unchecked, they can get thrown, too
(sacrificing generic DAO abstraction in terms of exceptions, though).

The following image shows the exception hierarchy that Spring provides.
(Note that the class hierarchy detailed in the image shows only a subset of the entire`DataAccessException` hierarchy.)

![DataAccessException](images/DataAccessException.png)

### [](#dao-annotations)2.2. Annotations Used to Configure DAO or Repository Classes ###

The best way to guarantee that your Data Access Objects (DAOs) or repositories provide
exception translation is to use the `@Repository` annotation. This annotation also
lets the component scanning support find and configure your DAOs and repositories
without having to provide XML configuration entries for them. The following example shows
how to use the `@Repository` annotation:

Java

```
@Repository (1)
public class SomeMovieFinder implements MovieFinder {
    // ...
}
```

|**1**|The `@Repository` annotation.|
|-----|-----------------------------|

Kotlin

```
@Repository (1)
class SomeMovieFinder : MovieFinder {
    // ...
}
```

|**1**|The `@Repository` annotation.|
|-----|-----------------------------|

Any DAO or repository implementation needs access to a persistence resource,
depending on the persistence technology used. For example, a JDBC-based repository
needs access to a JDBC `DataSource`, and a JPA-based repository needs access to an`EntityManager`. The easiest way to accomplish this is to have this resource dependency
injected by using one of the `@Autowired`, `@Inject`, `@Resource` or `@PersistenceContext`annotations. The following example works for a JPA repository:

Java

```
@Repository
public class JpaMovieFinder implements MovieFinder {

    @PersistenceContext
    private EntityManager entityManager;

    // ...
}
```

Kotlin

```
@Repository
class JpaMovieFinder : MovieFinder {

    @PersistenceContext
    private lateinit var entityManager: EntityManager

    // ...
}
```

If you use the classic Hibernate APIs, you can inject `SessionFactory`, as the following
example shows:

Java

```
@Repository
public class HibernateMovieFinder implements MovieFinder {

    private SessionFactory sessionFactory;

    @Autowired
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    // ...
}
```

Kotlin

```
@Repository
class HibernateMovieFinder(private val sessionFactory: SessionFactory) : MovieFinder {
    // ...
}
```

The last example we show here is for typical JDBC support. You could have the`DataSource` injected into an initialization method or a constructor, where you would create a`JdbcTemplate` and other data access support classes (such as `SimpleJdbcCall` and others) by using
this `DataSource`. The following example autowires a `DataSource`:

Java

```
@Repository
public class JdbcMovieFinder implements MovieFinder {

    private JdbcTemplate jdbcTemplate;

    @Autowired
    public void init(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    // ...
}
```

Kotlin

```
@Repository
class JdbcMovieFinder(dataSource: DataSource) : MovieFinder {

    private val jdbcTemplate = JdbcTemplate(dataSource)

    // ...
}
```

|   |See the specific coverage of each persistence technology for details on how to<br/>configure the application context to take advantage of these annotations.|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------|

[](#jdbc)3. Data Access with JDBC
----------

The value provided by the Spring Framework JDBC abstraction is perhaps best shown by
the sequence of actions outlined in the following table below. The table shows which actions Spring
takes care of and which actions are your responsibility.

|                         Action                         |Spring|You|
|--------------------------------------------------------|------|---|
|             Define connection parameters.              |      | X |
|                  Open the connection.                  |  X   |   |
|               Specify the SQL statement.               |      | X |
|    Declare parameters and provide parameter values     |      | X |
|             Prepare and run the statement.             |  X   |   |
|Set up the loop to iterate through the results (if any).|  X   |   |
|            Do the work for each iteration.             |      | X |
|                 Process any exception.                 |  X   |   |
|                  Handle transactions.                  |  X   |   |
|Close the connection, the statement, and the resultset. |  X   |   |

The Spring Framework takes care of all the low-level details that can make JDBC such a
tedious API.

### [](#jdbc-choose-style)3.1. Choosing an Approach for JDBC Database Access ###

You can choose among several approaches to form the basis for your JDBC database access.
In addition to three flavors of `JdbcTemplate`, a new `SimpleJdbcInsert` and`SimpleJdbcCall` approach optimizes database metadata, and the RDBMS Object style takes a
more object-oriented approach similar to that of JDO Query design. Once you start using
one of these approaches, you can still mix and match to include a feature from a
different approach. All approaches require a JDBC 2.0-compliant driver, and some
advanced features require a JDBC 3.0 driver.

* `JdbcTemplate` is the classic and most popular Spring JDBC approach. This
  “lowest-level” approach and all others use a JdbcTemplate under the covers.

* `NamedParameterJdbcTemplate` wraps a `JdbcTemplate` to provide named parameters
  instead of the traditional JDBC `?` placeholders. This approach provides better
  documentation and ease of use when you have multiple parameters for an SQL statement.

* `SimpleJdbcInsert` and `SimpleJdbcCall` optimize database metadata to limit the amount
  of necessary configuration. This approach simplifies coding so that you need to
  provide only the name of the table or procedure and provide a map of parameters matching
  the column names. This works only if the database provides adequate metadata. If the
  database does not provide this metadata, you have to provide explicit
  configuration of the parameters.

* RDBMS objects — including `MappingSqlQuery`, `SqlUpdate`, and `StoredProcedure`
  require you to create reusable and thread-safe objects during initialization of your
  data-access layer. This approach is modeled after JDO Query, wherein you define your
  query string, declare parameters, and compile the query. Once you do that,`execute(…​)`, `update(…​)`, and `findObject(…​)` methods can be called multiple
  times with various parameter values.

### [](#jdbc-packages)3.2. Package Hierarchy ###

The Spring Framework’s JDBC abstraction framework consists of four different packages:

* `core`: The `org.springframework.jdbc.core` package contains the `JdbcTemplate` class and its
  various callback interfaces, plus a variety of related classes. A subpackage named`org.springframework.jdbc.core.simple` contains the `SimpleJdbcInsert` and`SimpleJdbcCall` classes. Another subpackage named`org.springframework.jdbc.core.namedparam` contains the `NamedParameterJdbcTemplate`class and the related support classes. See [Using the JDBC Core Classes to Control Basic JDBC Processing and Error Handling](#jdbc-core), [JDBC Batch Operations](#jdbc-advanced-jdbc), and[Simplifying JDBC Operations with the `SimpleJdbc` Classes](#jdbc-simple-jdbc).

* `datasource`: The `org.springframework.jdbc.datasource` package contains a utility class for easy`DataSource` access and various simple `DataSource` implementations that you can use for
  testing and running unmodified JDBC code outside of a Java EE container. A subpackage
  named `org.springfamework.jdbc.datasource.embedded` provides support for creating
  embedded databases by using Java database engines, such as HSQL, H2, and Derby. See[Controlling Database Connections](#jdbc-connections) and [Embedded Database Support](#jdbc-embedded-database-support).

* `object`: The `org.springframework.jdbc.object` package contains classes that represent RDBMS
  queries, updates, and stored procedures as thread-safe, reusable objects. See[Modeling JDBC Operations as Java Objects](#jdbc-object). This approach is modeled by JDO, although objects returned by queries
  are naturally disconnected from the database. This higher-level of JDBC abstraction
  depends on the lower-level abstraction in the `org.springframework.jdbc.core` package.

* `support`: The `org.springframework.jdbc.support` package provides `SQLException` translation
  functionality and some utility classes. Exceptions thrown during JDBC processing are
  translated to exceptions defined in the `org.springframework.dao` package. This means
  that code using the Spring JDBC abstraction layer does not need to implement JDBC or
  RDBMS-specific error handling. All translated exceptions are unchecked, which gives you
  the option of catching the exceptions from which you can recover while letting other
  exceptions be propagated to the caller. See [Using `SQLExceptionTranslator`](#jdbc-SQLExceptionTranslator).

### [](#jdbc-core)3.3. Using the JDBC Core Classes to Control Basic JDBC Processing and Error Handling ###

This section covers how to use the JDBC core classes to control basic JDBC processing,
including error handling. It includes the following topics:

* [Using `JdbcTemplate`](#jdbc-JdbcTemplate)

* [Using `NamedParameterJdbcTemplate`](#jdbc-NamedParameterJdbcTemplate)

* [Using `SQLExceptionTranslator`](#jdbc-SQLExceptionTranslator)

* [Running Statements](#jdbc-statements-executing)

* [Running Queries](#jdbc-statements-querying)

* [Updating the Database](#jdbc-updates)

* [Retrieving Auto-generated Keys](#jdbc-auto-generated-keys)

#### [](#jdbc-JdbcTemplate)3.3.1. Using `JdbcTemplate` ####

`JdbcTemplate` is the central class in the JDBC core package. It handles the
creation and release of resources, which helps you avoid common errors, such as
forgetting to close the connection. It performs the basic tasks of the core JDBC
workflow (such as statement creation and execution), leaving application code to provide
SQL and extract results. The `JdbcTemplate` class:

* Runs SQL queries

* Updates statements and stored procedure calls

* Performs iteration over `ResultSet` instances and extraction of returned parameter values.

* Catches JDBC exceptions and translates them to the generic, more informative, exception
  hierarchy defined in the `org.springframework.dao` package. (See [Consistent Exception Hierarchy](#dao-exceptions).)

When you use the `JdbcTemplate` for your code, you need only to implement callback
interfaces, giving them a clearly defined contract. Given a `Connection` provided by the`JdbcTemplate` class, the `PreparedStatementCreator` callback interface creates a prepared
statement, providing SQL and any necessary parameters. The same is true for the`CallableStatementCreator` interface, which creates callable statements. The`RowCallbackHandler` interface extracts values from each row of a `ResultSet`.

You can use `JdbcTemplate` within a DAO implementation through direct instantiation
with a `DataSource` reference, or you can configure it in a Spring IoC container and give it to
DAOs as a bean reference.

|   |The `DataSource` should always be configured as a bean in the Spring IoC container. In<br/>the first case the bean is given to the service directly; in the second case it is given<br/>to the prepared template.|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

All SQL issued by this class is logged at the `DEBUG` level under the category
corresponding to the fully qualified class name of the template instance (typically`JdbcTemplate`, but it may be different if you use a custom subclass of the`JdbcTemplate` class).

The following sections provide some examples of `JdbcTemplate` usage. These examples
are not an exhaustive list of all of the functionality exposed by the `JdbcTemplate`.
See the attendant [javadoc](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/jdbc/core/JdbcTemplate.html) for that.

##### [](#jdbc-JdbcTemplate-examples-query)Querying (`SELECT`) #####

The following query gets the number of rows in a relation:

Java

```
int rowCount = this.jdbcTemplate.queryForObject("select count(*) from t_actor", Integer.class);
```

Kotlin

```
val rowCount = jdbcTemplate.queryForObject<Int>("select count(*) from t_actor")!!
```

The following query uses a bind variable:

Java

```
int countOfActorsNamedJoe = this.jdbcTemplate.queryForObject(
        "select count(*) from t_actor where first_name = ?", Integer.class, "Joe");
```

Kotlin

```
val countOfActorsNamedJoe = jdbcTemplate.queryForObject<Int>(
        "select count(*) from t_actor where first_name = ?", arrayOf("Joe"))!!
```

The following query looks for a `String`:

Java

```
String lastName = this.jdbcTemplate.queryForObject(
        "select last_name from t_actor where id = ?",
        String.class, 1212L);
```

Kotlin

```
val lastName = this.jdbcTemplate.queryForObject<String>(
        "select last_name from t_actor where id = ?",
        arrayOf(1212L))!!
```

The following query finds and populates a single domain object:

Java

```
Actor actor = jdbcTemplate.queryForObject(
        "select first_name, last_name from t_actor where id = ?",
        (resultSet, rowNum) -> {
            Actor newActor = new Actor();
            newActor.setFirstName(resultSet.getString("first_name"));
            newActor.setLastName(resultSet.getString("last_name"));
            return newActor;
        },
        1212L);
```

Kotlin

```
val actor = jdbcTemplate.queryForObject(
            "select first_name, last_name from t_actor where id = ?",
            arrayOf(1212L)) { rs, _ ->
        Actor(rs.getString("first_name"), rs.getString("last_name"))
    }
```

The following query finds and populates a list of domain objects:

Java

```
List<Actor> actors = this.jdbcTemplate.query(
        "select first_name, last_name from t_actor",
        (resultSet, rowNum) -> {
            Actor actor = new Actor();
            actor.setFirstName(resultSet.getString("first_name"));
            actor.setLastName(resultSet.getString("last_name"));
            return actor;
        });
```

Kotlin

```
val actors = jdbcTemplate.query("select first_name, last_name from t_actor") { rs, _ ->
        Actor(rs.getString("first_name"), rs.getString("last_name"))
```

If the last two snippets of code actually existed in the same application, it would make
sense to remove the duplication present in the two `RowMapper` lambda expressions and
extract them out into a single field that could then be referenced by DAO methods as needed.
For example, it may be better to write the preceding code snippet as follows:

Java

```
private final RowMapper<Actor> actorRowMapper = (resultSet, rowNum) -> {
    Actor actor = new Actor();
    actor.setFirstName(resultSet.getString("first_name"));
    actor.setLastName(resultSet.getString("last_name"));
    return actor;
};

public List<Actor> findAllActors() {
    return this.jdbcTemplate.query("select first_name, last_name from t_actor", actorRowMapper);
}
```

Kotlin

```
val actorMapper = RowMapper<Actor> { rs: ResultSet, rowNum: Int ->
    Actor(rs.getString("first_name"), rs.getString("last_name"))
}

fun findAllActors(): List<Actor> {
    return jdbcTemplate.query("select first_name, last_name from t_actor", actorMapper)
}
```

##### [](#jdbc-JdbcTemplate-examples-update)Updating (`INSERT`, `UPDATE`, and `DELETE`) with `JdbcTemplate` #####

You can use the `update(..)` method to perform insert, update, and delete operations.
Parameter values are usually provided as variable arguments or, alternatively, as an object array.

The following example inserts a new entry:

Java

```
this.jdbcTemplate.update(
        "insert into t_actor (first_name, last_name) values (?, ?)",
        "Leonor", "Watling");
```

Kotlin

```
jdbcTemplate.update(
        "insert into t_actor (first_name, last_name) values (?, ?)",
        "Leonor", "Watling")
```

The following example updates an existing entry:

Java

```
this.jdbcTemplate.update(
        "update t_actor set last_name = ? where id = ?",
        "Banjo", 5276L);
```

Kotlin

```
jdbcTemplate.update(
        "update t_actor set last_name = ? where id = ?",
        "Banjo", 5276L)
```

The following example deletes an entry:

Java

```
this.jdbcTemplate.update(
        "delete from t_actor where id = ?",
        Long.valueOf(actorId));
```

Kotlin

```
jdbcTemplate.update("delete from t_actor where id = ?", actorId.toLong())
```

##### [](#jdbc-JdbcTemplate-examples-other)Other `JdbcTemplate` Operations #####

You can use the `execute(..)` method to run any arbitrary SQL. Consequently, the
method is often used for DDL statements. It is heavily overloaded with variants that take
callback interfaces, binding variable arrays, and so on. The following example creates a
table:

Java

```
this.jdbcTemplate.execute("create table mytable (id integer, name varchar(100))");
```

Kotlin

```
jdbcTemplate.execute("create table mytable (id integer, name varchar(100))")
```

The following example invokes a stored procedure:

Java

```
this.jdbcTemplate.update(
        "call SUPPORT.REFRESH_ACTORS_SUMMARY(?)",
        Long.valueOf(unionId));
```

Kotlin

```
jdbcTemplate.update(
        "call SUPPORT.REFRESH_ACTORS_SUMMARY(?)",
        unionId.toLong())
```

More sophisticated stored procedure support is [covered later](#jdbc-StoredProcedure).

##### [](#jdbc-JdbcTemplate-idioms)`JdbcTemplate` Best Practices #####

Instances of the `JdbcTemplate` class are thread-safe, once configured. This is
important because it means that you can configure a single instance of a `JdbcTemplate`and then safely inject this shared reference into multiple DAOs (or repositories).
The `JdbcTemplate` is stateful, in that it maintains a reference to a `DataSource`, but
this state is not conversational state.

A common practice when using the `JdbcTemplate` class (and the associated[`NamedParameterJdbcTemplate`](#jdbc-NamedParameterJdbcTemplate) class) is to
configure a `DataSource` in your Spring configuration file and then dependency-inject
that shared `DataSource` bean into your DAO classes. The `JdbcTemplate` is created in
the setter for the `DataSource`. This leads to DAOs that resemble the following:

Java

```
public class JdbcCorporateEventDao implements CorporateEventDao {

    private JdbcTemplate jdbcTemplate;

    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    // JDBC-backed implementations of the methods on the CorporateEventDao follow...
}
```

Kotlin

```
class JdbcCorporateEventDao(dataSource: DataSource) : CorporateEventDao {

    private val jdbcTemplate = JdbcTemplate(dataSource)

    // JDBC-backed implementations of the methods on the CorporateEventDao follow...
}
```

The following example shows the corresponding XML configuration:

```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="corporateEventDao" class="com.example.JdbcCorporateEventDao">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <context:property-placeholder location="jdbc.properties"/>

</beans>
```

An alternative to explicit configuration is to use component-scanning and annotation
support for dependency injection. In this case, you can annotate the class with `@Repository`(which makes it a candidate for component-scanning) and annotate the `DataSource` setter
method with `@Autowired`. The following example shows how to do so:

Java

```
@Repository (1)
public class JdbcCorporateEventDao implements CorporateEventDao {

    private JdbcTemplate jdbcTemplate;

    @Autowired (2)
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource); (3)
    }

    // JDBC-backed implementations of the methods on the CorporateEventDao follow...
}
```

|**1**|          Annotate the class with `@Repository`.          |
|-----|----------------------------------------------------------|
|**2**|Annotate the `DataSource` setter method with `@Autowired`.|
|**3**|    Create a new `JdbcTemplate` with the `DataSource`.    |

Kotlin

```
@Repository (1)
class JdbcCorporateEventDao(dataSource: DataSource) : CorporateEventDao { (2)

    private val jdbcTemplate = JdbcTemplate(dataSource) (3)

    // JDBC-backed implementations of the methods on the CorporateEventDao follow...
}
```

|**1**|      Annotate the class with `@Repository`.      |
|-----|--------------------------------------------------|
|**2**|    Constructor injection of the `DataSource`.    |
|**3**|Create a new `JdbcTemplate` with the `DataSource`.|

The following example shows the corresponding XML configuration:

```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- Scans within the base package of the application for @Component classes to configure as beans -->
    <context:component-scan base-package="org.springframework.docs.test" />

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <context:property-placeholder location="jdbc.properties"/>

</beans>
```

If you use Spring’s `JdbcDaoSupport` class and your various JDBC-backed DAO classes
extend from it, your sub-class inherits a `setDataSource(..)` method from the`JdbcDaoSupport` class. You can choose whether to inherit from this class. The`JdbcDaoSupport` class is provided as a convenience only.

Regardless of which of the above template initialization styles you choose to use (or
not), it is seldom necessary to create a new instance of a `JdbcTemplate` class each
time you want to run SQL. Once configured, a `JdbcTemplate` instance is thread-safe.
If your application accesses multiple
databases, you may want multiple `JdbcTemplate` instances, which requires multiple `DataSources` and, subsequently, multiple differently
configured `JdbcTemplate` instances.

#### [](#jdbc-NamedParameterJdbcTemplate)3.3.2. Using `NamedParameterJdbcTemplate` ####

The `NamedParameterJdbcTemplate` class adds support for programming JDBC statements
by using named parameters, as opposed to programming JDBC statements using only classic
placeholder ( `'?'`) arguments. The `NamedParameterJdbcTemplate` class wraps a`JdbcTemplate` and delegates to the wrapped `JdbcTemplate` to do much of its work. This
section describes only those areas of the `NamedParameterJdbcTemplate` class that differ
from the `JdbcTemplate` itself — namely, programming JDBC statements by using named
parameters. The following example shows how to use `NamedParameterJdbcTemplate`:

Java

```
// some JDBC-backed DAO class...
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

public void setDataSource(DataSource dataSource) {
    this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
}

public int countOfActorsByFirstName(String firstName) {

    String sql = "select count(*) from T_ACTOR where first_name = :first_name";

    SqlParameterSource namedParameters = new MapSqlParameterSource("first_name", firstName);

    return this.namedParameterJdbcTemplate.queryForObject(sql, namedParameters, Integer.class);
}
```

Kotlin

```
private val namedParameterJdbcTemplate = NamedParameterJdbcTemplate(dataSource)

fun countOfActorsByFirstName(firstName: String): Int {
    val sql = "select count(*) from T_ACTOR where first_name = :first_name"
    val namedParameters = MapSqlParameterSource("first_name", firstName)
    return namedParameterJdbcTemplate.queryForObject(sql, namedParameters, Int::class.java)!!
}
```

Notice the use of the named parameter notation in the value assigned to the `sql`variable and the corresponding value that is plugged into the `namedParameters`variable (of type `MapSqlParameterSource`).

Alternatively, you can pass along named parameters and their corresponding values to a`NamedParameterJdbcTemplate` instance by using the `Map`-based style. The remaining
methods exposed by the `NamedParameterJdbcOperations` and implemented by the`NamedParameterJdbcTemplate` class follow a similar pattern and are not covered here.

The following example shows the use of the `Map`-based style:

Java

```
// some JDBC-backed DAO class...
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

public void setDataSource(DataSource dataSource) {
    this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
}

public int countOfActorsByFirstName(String firstName) {

    String sql = "select count(*) from T_ACTOR where first_name = :first_name";

    Map<String, String> namedParameters = Collections.singletonMap("first_name", firstName);

    return this.namedParameterJdbcTemplate.queryForObject(sql, namedParameters,  Integer.class);
}
```

Kotlin

```
// some JDBC-backed DAO class...
private val namedParameterJdbcTemplate = NamedParameterJdbcTemplate(dataSource)

fun countOfActorsByFirstName(firstName: String): Int {
    val sql = "select count(*) from T_ACTOR where first_name = :first_name"
    val namedParameters = mapOf("first_name" to firstName)
    return namedParameterJdbcTemplate.queryForObject(sql, namedParameters, Int::class.java)!!
}
```

One nice feature related to the `NamedParameterJdbcTemplate` (and existing in the same
Java package) is the `SqlParameterSource` interface. You have already seen an example of
an implementation of this interface in one of the previous code snippets (the`MapSqlParameterSource` class). An `SqlParameterSource` is a source of named parameter
values to a `NamedParameterJdbcTemplate`. The `MapSqlParameterSource` class is a
simple implementation that is an adapter around a `java.util.Map`, where the keys
are the parameter names and the values are the parameter values.

Another `SqlParameterSource` implementation is the `BeanPropertySqlParameterSource`class. This class wraps an arbitrary JavaBean (that is, an instance of a class that
adheres to [the
JavaBean conventions](https://www.oracle.com/technetwork/java/javase/documentation/spec-136004.html)) and uses the properties of the wrapped JavaBean as the source
of named parameter values.

The following example shows a typical JavaBean:

Java

```
public class Actor {

    private Long id;
    private String firstName;
    private String lastName;

    public String getFirstName() {
        return this.firstName;
    }

    public String getLastName() {
        return this.lastName;
    }

    public Long getId() {
        return this.id;
    }

    // setters omitted...

}
```

Kotlin

```
data class Actor(val id: Long, val firstName: String, val lastName: String)
```

The following example uses a `NamedParameterJdbcTemplate` to return the count of the
members of the class shown in the preceding example:

Java

```
// some JDBC-backed DAO class...
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

public void setDataSource(DataSource dataSource) {
    this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
}

public int countOfActors(Actor exampleActor) {

    // notice how the named parameters match the properties of the above 'Actor' class
    String sql = "select count(*) from T_ACTOR where first_name = :firstName and last_name = :lastName";

    SqlParameterSource namedParameters = new BeanPropertySqlParameterSource(exampleActor);

    return this.namedParameterJdbcTemplate.queryForObject(sql, namedParameters, Integer.class);
}
```

Kotlin

```
// some JDBC-backed DAO class...
private val namedParameterJdbcTemplate = NamedParameterJdbcTemplate(dataSource)

private val namedParameterJdbcTemplate = NamedParameterJdbcTemplate(dataSource)

fun countOfActors(exampleActor: Actor): Int {
    // notice how the named parameters match the properties of the above 'Actor' class
    val sql = "select count(*) from T_ACTOR where first_name = :firstName and last_name = :lastName"
    val namedParameters = BeanPropertySqlParameterSource(exampleActor)
    return namedParameterJdbcTemplate.queryForObject(sql, namedParameters, Int::class.java)!!
}
```

Remember that the `NamedParameterJdbcTemplate` class wraps a classic `JdbcTemplate`template. If you need access to the wrapped `JdbcTemplate` instance to access
functionality that is present only in the `JdbcTemplate` class, you can use the`getJdbcOperations()` method to access the wrapped `JdbcTemplate` through the`JdbcOperations` interface.

See also [`JdbcTemplate` Best Practices](#jdbc-JdbcTemplate-idioms) for guidelines on using the`NamedParameterJdbcTemplate` class in the context of an application.

#### [](#jdbc-SQLExceptionTranslator)3.3.3. Using `SQLExceptionTranslator` ####

`SQLExceptionTranslator` is an interface to be implemented by classes that can translate
between `SQLException`s and Spring’s own `org.springframework.dao.DataAccessException`,
which is agnostic in regard to data access strategy. Implementations can be generic (for
example, using SQLState codes for JDBC) or proprietary (for example, using Oracle error
codes) for greater precision.

`SQLErrorCodeSQLExceptionTranslator` is the implementation of `SQLExceptionTranslator`that is used by default. This implementation uses specific vendor codes. It is more
precise than the `SQLState` implementation. The error code translations are based on
codes held in a JavaBean type class called `SQLErrorCodes`. This class is created and
populated by an `SQLErrorCodesFactory`, which (as the name suggests) is a factory for
creating `SQLErrorCodes` based on the contents of a configuration file named`sql-error-codes.xml`. This file is populated with vendor codes and based on the`DatabaseProductName` taken from `DatabaseMetaData`. The codes for the actual
database you are using are used.

The `SQLErrorCodeSQLExceptionTranslator` applies matching rules in the following sequence:

1. Any custom translation implemented by a subclass. Normally, the provided concrete`SQLErrorCodeSQLExceptionTranslator` is used, so this rule does not apply. It
   applies only if you have actually provided a subclass implementation.

2. Any custom implementation of the `SQLExceptionTranslator` interface that is provided
   as the `customSqlExceptionTranslator` property of the `SQLErrorCodes` class.

3. The list of instances of the `CustomSQLErrorCodesTranslation` class (provided for the`customTranslations` property of the `SQLErrorCodes` class) are searched for a match.

4. Error code matching is applied.

5. Use the fallback translator. `SQLExceptionSubclassTranslator` is the default fallback
   translator. If this translation is not available, the next fallback translator is
   the `SQLStateSQLExceptionTranslator`.

|   |The `SQLErrorCodesFactory` is used by default to define `Error` codes and custom exception<br/>translations. They are looked up in a file named `sql-error-codes.xml` from the<br/>classpath, and the matching `SQLErrorCodes` instance is located based on the database<br/>name from the database metadata of the database in use.|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

You can extend `SQLErrorCodeSQLExceptionTranslator`, as the following example shows:

Java

```
public class CustomSQLErrorCodesTranslator extends SQLErrorCodeSQLExceptionTranslator {

    protected DataAccessException customTranslate(String task, String sql, SQLException sqlEx) {
        if (sqlEx.getErrorCode() == -12345) {
            return new DeadlockLoserDataAccessException(task, sqlEx);
        }
        return null;
    }
}
```

Kotlin

```
class CustomSQLErrorCodesTranslator : SQLErrorCodeSQLExceptionTranslator() {

    override fun customTranslate(task: String, sql: String?, sqlEx: SQLException): DataAccessException? {
        if (sqlEx.errorCode == -12345) {
            return DeadlockLoserDataAccessException(task, sqlEx)
        }
        return null
    }
}
```

In the preceding example, the specific error code (`-12345`) is translated, while other errors are
left to be translated by the default translator implementation. To use this custom
translator, you must pass it to the `JdbcTemplate` through the method`setExceptionTranslator`, and you must use this `JdbcTemplate` for all of the data access
processing where this translator is needed. The following example shows how you can use this custom
translator:

Java

```
private JdbcTemplate jdbcTemplate;

public void setDataSource(DataSource dataSource) {

    // create a JdbcTemplate and set data source
    this.jdbcTemplate = new JdbcTemplate();
    this.jdbcTemplate.setDataSource(dataSource);

    // create a custom translator and set the DataSource for the default translation lookup
    CustomSQLErrorCodesTranslator tr = new CustomSQLErrorCodesTranslator();
    tr.setDataSource(dataSource);
    this.jdbcTemplate.setExceptionTranslator(tr);

}

public void updateShippingCharge(long orderId, long pct) {
    // use the prepared JdbcTemplate for this update
    this.jdbcTemplate.update("update orders" +
        " set shipping_charge = shipping_charge * ? / 100" +
        " where id = ?", pct, orderId);
}
```

Kotlin

```
// create a JdbcTemplate and set data source
private val jdbcTemplate = JdbcTemplate(dataSource).apply {
    // create a custom translator and set the DataSource for the default translation lookup
    exceptionTranslator = CustomSQLErrorCodesTranslator().apply {
        this.dataSource = dataSource
    }
}

fun updateShippingCharge(orderId: Long, pct: Long) {
    // use the prepared JdbcTemplate for this update
    this.jdbcTemplate!!.update("update orders" +
            " set shipping_charge = shipping_charge * ? / 100" +
            " where id = ?", pct, orderId)
}
```

The custom translator is passed a data source in order to look up the error codes in`sql-error-codes.xml`.

#### [](#jdbc-statements-executing)3.3.4. Running Statements ####

Running an SQL statement requires very little code. You need a `DataSource` and a`JdbcTemplate`, including the convenience methods that are provided with the`JdbcTemplate`. The following example shows what you need to include for a minimal but
fully functional class that creates a new table:

Java

```
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;

public class ExecuteAStatement {

    private JdbcTemplate jdbcTemplate;

    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    public void doExecute() {
        this.jdbcTemplate.execute("create table mytable (id integer, name varchar(100))");
    }
}
```

Kotlin

```
import javax.sql.DataSource
import org.springframework.jdbc.core.JdbcTemplate

class ExecuteAStatement(dataSource: DataSource) {

    private val jdbcTemplate = JdbcTemplate(dataSource)

    fun doExecute() {
        jdbcTemplate.execute("create table mytable (id integer, name varchar(100))")
    }
}
```

#### [](#jdbc-statements-querying)3.3.5. Running Queries ####

Some query methods return a single value. To retrieve a count or a specific value from
one row, use `queryForObject(..)`. The latter converts the returned JDBC `Type` to the
Java class that is passed in as an argument. If the type conversion is invalid, an`InvalidDataAccessApiUsageException` is thrown. The following example contains two
query methods, one for an `int` and one that queries for a `String`:

Java

```
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;

public class RunAQuery {

    private JdbcTemplate jdbcTemplate;

    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    public int getCount() {
        return this.jdbcTemplate.queryForObject("select count(*) from mytable", Integer.class);
    }

    public String getName() {
        return this.jdbcTemplate.queryForObject("select name from mytable", String.class);
    }
}
```

Kotlin

```
import javax.sql.DataSource
import org.springframework.jdbc.core.JdbcTemplate

class RunAQuery(dataSource: DataSource) {

    private val jdbcTemplate = JdbcTemplate(dataSource)

    val count: Int
        get() = jdbcTemplate.queryForObject("select count(*) from mytable")!!

    val name: String?
        get() = jdbcTemplate.queryForObject("select name from mytable")
}
```

In addition to the single result query methods, several methods return a list with an
entry for each row that the query returned. The most generic method is `queryForList(..)`,
which returns a `List` where each element is a `Map` containing one entry for each column,
using the column name as the key. If you add a method to the preceding example to retrieve a
list of all the rows, it might be as follows:

Java

```
private JdbcTemplate jdbcTemplate;

public void setDataSource(DataSource dataSource) {
    this.jdbcTemplate = new JdbcTemplate(dataSource);
}

public List<Map<String, Object>> getList() {
    return this.jdbcTemplate.queryForList("select * from mytable");
}
```

Kotlin

```
private val jdbcTemplate = JdbcTemplate(dataSource)

fun getList(): List<Map<String, Any>> {
    return jdbcTemplate.queryForList("select * from mytable")
}
```

The returned list would resemble the following:

```
[{name=Bob, id=1}, {name=Mary, id=2}]
```

#### [](#jdbc-updates)3.3.6. Updating the Database ####

The following example updates a column for a certain primary key:

Java

```
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;

public class ExecuteAnUpdate {

    private JdbcTemplate jdbcTemplate;

    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    public void setName(int id, String name) {
        this.jdbcTemplate.update("update mytable set name = ? where id = ?", name, id);
    }
}
```

Kotlin

```
import javax.sql.DataSource
import org.springframework.jdbc.core.JdbcTemplate

class ExecuteAnUpdate(dataSource: DataSource) {

    private val jdbcTemplate = JdbcTemplate(dataSource)

    fun setName(id: Int, name: String) {
        jdbcTemplate.update("update mytable set name = ? where id = ?", name, id)
    }
}
```

In the preceding example,
an SQL statement has placeholders for row parameters. You can pass the parameter values
in as varargs or, alternatively, as an array of objects. Thus, you should explicitly wrap primitives
in the primitive wrapper classes, or you should use auto-boxing.

#### [](#jdbc-auto-generated-keys)3.3.7. Retrieving Auto-generated Keys ####

An `update()` convenience method supports the retrieval of primary keys generated by the
database. This support is part of the JDBC 3.0 standard. See Chapter 13.6 of the
specification for details. The method takes a `PreparedStatementCreator` as its first
argument, and this is the way the required insert statement is specified. The other
argument is a `KeyHolder`, which contains the generated key on successful return from the
update. There is no standard single way to create an appropriate `PreparedStatement`(which explains why the method signature is the way it is). The following example works
on Oracle but may not work on other platforms:

Java

```
final String INSERT_SQL = "insert into my_test (name) values(?)";
final String name = "Rob";

KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(connection -> {
    PreparedStatement ps = connection.prepareStatement(INSERT_SQL, new String[] { "id" });
    ps.setString(1, name);
    return ps;
}, keyHolder);

// keyHolder.getKey() now contains the generated key
```

Kotlin

```
val INSERT_SQL = "insert into my_test (name) values(?)"
val name = "Rob"

val keyHolder = GeneratedKeyHolder()
jdbcTemplate.update({
    it.prepareStatement (INSERT_SQL, arrayOf("id")).apply { setString(1, name) }
}, keyHolder)

// keyHolder.getKey() now contains the generated key
```

### [](#jdbc-connections)3.4. Controlling Database Connections ###

This section covers:

* [Using `DataSource`](#jdbc-datasource)

* [Using `DataSourceUtils`](#jdbc-DataSourceUtils)

* [Implementing `SmartDataSource`](#jdbc-SmartDataSource)

* [Extending `AbstractDataSource`](#jdbc-AbstractDataSource)

* [Using `SingleConnectionDataSource`](#jdbc-SingleConnectionDataSource)

* [Using `DriverManagerDataSource`](#jdbc-DriverManagerDataSource)

* [Using `TransactionAwareDataSourceProxy`](#jdbc-TransactionAwareDataSourceProxy)

* [Using `DataSourceTransactionManager`](#jdbc-DataSourceTransactionManager)

#### [](#jdbc-datasource)3.4.1. Using `DataSource` ####

Spring obtains a connection to the database through a `DataSource`. A `DataSource` is
part of the JDBC specification and is a generalized connection factory. It lets a
container or a framework hide connection pooling and transaction management issues
from the application code. As a developer, you need not know details about how to
connect to the database. That is the responsibility of the administrator who sets up
the datasource. You most likely fill both roles as you develop and test code, but you
do not necessarily have to know how the production data source is configured.

When you use Spring’s JDBC layer, you can obtain a data source from JNDI, or you can
configure your own with a connection pool implementation provided by a third party.
Traditional choices are Apache Commons DBCP and C3P0 with bean-style `DataSource` classes;
for a modern JDBC connection pool, consider HikariCP with its builder-style API instead.

|   |You should use the `DriverManagerDataSource` and `SimpleDriverDataSource` classes<br/>(as included in the Spring distribution) only for testing purposes! Those variants do not<br/>provide pooling and perform poorly when multiple requests for a connection are made.|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

The following section uses Spring’s `DriverManagerDataSource` implementation.
Several other `DataSource` variants are covered later.

To configure a `DriverManagerDataSource`:

1. Obtain a connection with `DriverManagerDataSource` as you typically obtain a JDBC
   connection.

2. Specify the fully qualified classname of the JDBC driver so that the `DriverManager`can load the driver class.

3. Provide a URL that varies between JDBC drivers. (See the documentation for your driver
   for the correct value.)

4. Provide a username and a password to connect to the database.

The following example shows how to configure a `DriverManagerDataSource` in Java:

Java

```
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.hsqldb.jdbcDriver");
dataSource.setUrl("jdbc:hsqldb:hsql://localhost:");
dataSource.setUsername("sa");
dataSource.setPassword("");
```

Kotlin

```
val dataSource = DriverManagerDataSource().apply {
    setDriverClassName("org.hsqldb.jdbcDriver")
    url = "jdbc:hsqldb:hsql://localhost:"
    username = "sa"
    password = ""
}
```

The following example shows the corresponding XML configuration:

```
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${jdbc.driverClassName}"/>
    <property name="url" value="${jdbc.url}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>

<context:property-placeholder location="jdbc.properties"/>
```

The next two examples show the basic connectivity and configuration for DBCP and C3P0.
To learn about more options that help control the pooling features, see the product
documentation for the respective connection pooling implementations.

The following example shows DBCP configuration:

```
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="${jdbc.driverClassName}"/>
    <property name="url" value="${jdbc.url}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>

<context:property-placeholder location="jdbc.properties"/>
```

The following example shows C3P0 configuration:

```
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
    <property name="driverClass" value="${jdbc.driverClassName}"/>
    <property name="jdbcUrl" value="${jdbc.url}"/>
    <property name="user" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>

<context:property-placeholder location="jdbc.properties"/>
```

#### [](#jdbc-DataSourceUtils)3.4.2. Using `DataSourceUtils` ####

The `DataSourceUtils` class is a convenient and powerful helper class that provides`static` methods to obtain connections from JNDI and close connections if necessary. It
supports thread-bound connections with, for example, `DataSourceTransactionManager`.

#### [](#jdbc-SmartDataSource)3.4.3. Implementing `SmartDataSource` ####

The `SmartDataSource` interface should be implemented by classes that can provide a
connection to a relational database. It extends the `DataSource` interface to let
classes that use it query whether the connection should be closed after a given
operation. This usage is efficient when you know that you need to reuse a connection.

#### [](#jdbc-AbstractDataSource)3.4.4. Extending `AbstractDataSource` ####

`AbstractDataSource` is an `abstract` base class for Spring’s `DataSource`implementations. It implements code that is common to all `DataSource` implementations.
You should extend the `AbstractDataSource` class if you write your own `DataSource`implementation.

#### [](#jdbc-SingleConnectionDataSource)3.4.5. Using `SingleConnectionDataSource` ####

The `SingleConnectionDataSource` class is an implementation of the `SmartDataSource`interface that wraps a single `Connection` that is not closed after each use.
This is not multi-threading capable.

If any client code calls `close` on the assumption of a pooled connection (as when using
persistence tools), you should set the `suppressClose` property to `true`. This setting
returns a close-suppressing proxy that wraps the physical connection. Note that you can
no longer cast this to a native Oracle `Connection` or a similar object.

`SingleConnectionDataSource` is primarily a test class. It typically enables easy testing
of code outside an application server, in conjunction with a simple JNDI environment.
In contrast to `DriverManagerDataSource`, it reuses the same connection all the time,
avoiding excessive creation of physical connections.

#### [](#jdbc-DriverManagerDataSource)3.4.6. Using `DriverManagerDataSource` ####

The `DriverManagerDataSource` class is an implementation of the standard `DataSource`interface that configures a plain JDBC driver through bean properties and returns a new`Connection` every time.

This implementation is useful for test and stand-alone environments outside of a Java EE
container, either as a `DataSource` bean in a Spring IoC container or in conjunction
with a simple JNDI environment. Pool-assuming `Connection.close()` calls
close the connection, so any `DataSource`-aware persistence code should work. However,
using JavaBean-style connection pools (such as `commons-dbcp`) is so easy, even in a test
environment, that it is almost always preferable to use such a connection pool over`DriverManagerDataSource`.

#### [](#jdbc-TransactionAwareDataSourceProxy)3.4.7. Using `TransactionAwareDataSourceProxy` ####

`TransactionAwareDataSourceProxy` is a proxy for a target `DataSource`. The proxy wraps that
target `DataSource` to add awareness of Spring-managed transactions. In this respect, it
is similar to a transactional JNDI `DataSource`, as provided by a Java EE server.

|   |It is rarely desirable to use this class, except when already existing code must be<br/>called and passed a standard JDBC `DataSource` interface implementation. In this case,<br/>you can still have this code be usable and, at the same time, have this code<br/>participating in Spring managed transactions. It is generally preferable to write your<br/>own new code by using the higher level abstractions for resource management, such as`JdbcTemplate` or `DataSourceUtils`.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

See the [`TransactionAwareDataSourceProxy`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/jdbc/datasource/TransactionAwareDataSourceProxy.html)javadoc for more details.

#### [](#jdbc-DataSourceTransactionManager)3.4.8. Using `DataSourceTransactionManager` ####

The `DataSourceTransactionManager` class is a `PlatformTransactionManager`implementation for single JDBC datasources. It binds a JDBC connection from the
specified data source to the currently executing thread, potentially allowing for one
thread connection per data source.

Application code is required to retrieve the JDBC connection through`DataSourceUtils.getConnection(DataSource)` instead of Java EE’s standard`DataSource.getConnection`. It throws unchecked `org.springframework.dao` exceptions
instead of checked `SQLExceptions`. All framework classes (such as `JdbcTemplate`) use this
strategy implicitly. If not used with this transaction manager, the lookup strategy
behaves exactly like the common one. Thus, it can be used in any case.

The `DataSourceTransactionManager` class supports custom isolation levels and timeouts
that get applied as appropriate JDBC statement query timeouts. To support the latter,
application code must either use `JdbcTemplate` or call the`DataSourceUtils.applyTransactionTimeout(..)` method for each created statement.

You can use this implementation instead of `JtaTransactionManager` in the single-resource
case, as it does not require the container to support JTA. Switching between
both is just a matter of configuration, provided you stick to the required connection lookup
pattern. JTA does not support custom isolation levels.

### [](#jdbc-advanced-jdbc)3.5. JDBC Batch Operations ###

Most JDBC drivers provide improved performance if you batch multiple calls to the same
prepared statement. By grouping updates into batches, you limit the number of round trips
to the database.

#### [](#jdbc-batch-classic)3.5.1. Basic Batch Operations with `JdbcTemplate` ####

You accomplish `JdbcTemplate` batch processing by implementing two methods of a special
interface, `BatchPreparedStatementSetter`, and passing that implementation in as the second parameter
in your `batchUpdate` method call. You can use the `getBatchSize` method to provide the size of
the current batch. You can use the `setValues` method to set the values for the parameters of
the prepared statement. This method is called the number of times that you
specified in the `getBatchSize` call. The following example updates the `t_actor` table
based on entries in a list, and the entire list is used as the batch:

Java

```
public class JdbcActorDao implements ActorDao {

    private JdbcTemplate jdbcTemplate;

    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    public int[] batchUpdate(final List<Actor> actors) {
        return this.jdbcTemplate.batchUpdate(
                "update t_actor set first_name = ?, last_name = ? where id = ?",
                new BatchPreparedStatementSetter() {
                    public void setValues(PreparedStatement ps, int i) throws SQLException {
                        Actor actor = actors.get(i);
                        ps.setString(1, actor.getFirstName());
                        ps.setString(2, actor.getLastName());
                        ps.setLong(3, actor.getId().longValue());
                    }
                    public int getBatchSize() {
                        return actors.size();
                    }
                });
    }

    // ... additional methods
}
```

Kotlin

```
class JdbcActorDao(dataSource: DataSource) : ActorDao {

    private val jdbcTemplate = JdbcTemplate(dataSource)

    fun batchUpdate(actors: List<Actor>): IntArray {
        return jdbcTemplate.batchUpdate(
                "update t_actor set first_name = ?, last_name = ? where id = ?",
                object: BatchPreparedStatementSetter {
                    override fun setValues(ps: PreparedStatement, i: Int) {
                        ps.setString(1, actors[i].firstName)
                        ps.setString(2, actors[i].lastName)
                        ps.setLong(3, actors[i].id)
                    }

                    override fun getBatchSize() = actors.size
                })
    }

    // ... additional methods
}
```

If you process a stream of updates or reading from a file, you might have a
preferred batch size, but the last batch might not have that number of entries. In this
case, you can use the `InterruptibleBatchPreparedStatementSetter` interface, which lets
you interrupt a batch once the input source is exhausted. The `isBatchExhausted` method
lets you signal the end of the batch.

#### [](#jdbc-batch-list)3.5.2. Batch Operations with a List of Objects ####

Both the `JdbcTemplate` and the `NamedParameterJdbcTemplate` provides an alternate way
of providing the batch update. Instead of implementing a special batch interface, you
provide all parameter values in the call as a list. The framework loops over these
values and uses an internal prepared statement setter. The API varies, depending on
whether you use named parameters. For the named parameters, you provide an array of`SqlParameterSource`, one entry for each member of the batch. You can use the`SqlParameterSourceUtils.createBatch` convenience methods to create this array, passing
in an array of bean-style objects (with getter methods corresponding to parameters),`String`-keyed `Map` instances (containing the corresponding parameters as values), or a mix of both.

The following example shows a batch update using named parameters:

Java

```
public class JdbcActorDao implements ActorDao {

    private NamedParameterTemplate namedParameterJdbcTemplate;

    public void setDataSource(DataSource dataSource) {
        this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
    }

    public int[] batchUpdate(List<Actor> actors) {
        return this.namedParameterJdbcTemplate.batchUpdate(
                "update t_actor set first_name = :firstName, last_name = :lastName where id = :id",
                SqlParameterSourceUtils.createBatch(actors));
    }

    // ... additional methods
}
```

Kotlin

```
class JdbcActorDao(dataSource: DataSource) : ActorDao {

    private val namedParameterJdbcTemplate = NamedParameterJdbcTemplate(dataSource)

    fun batchUpdate(actors: List<Actor>): IntArray {
        return this.namedParameterJdbcTemplate.batchUpdate(
                "update t_actor set first_name = :firstName, last_name = :lastName where id = :id",
                SqlParameterSourceUtils.createBatch(actors));
    }

        // ... additional methods
}
```

For an SQL statement that uses the classic `?` placeholders, you pass in a list
containing an object array with the update values. This object array must have one entry
for each placeholder in the SQL statement, and they must be in the same order as they are
defined in the SQL statement.

The following example is the same as the preceding example, except that it uses classic
JDBC `?` placeholders:

Java

```
public class JdbcActorDao implements ActorDao {

    private JdbcTemplate jdbcTemplate;

    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    public int[] batchUpdate(final List<Actor> actors) {
        List<Object[]> batch = new ArrayList<Object[]>();
        for (Actor actor : actors) {
            Object[] values = new Object[] {
                    actor.getFirstName(), actor.getLastName(), actor.getId()};
            batch.add(values);
        }
        return this.jdbcTemplate.batchUpdate(
                "update t_actor set first_name = ?, last_name = ? where id = ?",
                batch);
    }

    // ... additional methods
}
```

Kotlin

```
class JdbcActorDao(dataSource: DataSource) : ActorDao {

    private val jdbcTemplate = JdbcTemplate(dataSource)

    fun batchUpdate(actors: List<Actor>): IntArray {
        val batch = mutableListOf<Array<Any>>()
        for (actor in actors) {
            batch.add(arrayOf(actor.firstName, actor.lastName, actor.id))
        }
        return jdbcTemplate.batchUpdate(
                "update t_actor set first_name = ?, last_name = ? where id = ?", batch)
    }

    // ... additional methods
}
```

All of the batch update methods that we described earlier return an `int` array
containing the number of affected rows for each batch entry. This count is reported by
the JDBC driver. If the count is not available, the JDBC driver returns a value of `-2`.

|   |In such a scenario, with automatic setting of values on an underlying `PreparedStatement`,<br/>the corresponding JDBC type for each value needs to be derived from the given Java type.<br/>While this usually works well, there is a potential for issues (for example, with Map-contained`null` values). Spring, by default, calls `ParameterMetaData.getParameterType` in such a<br/>case, which can be expensive with your JDBC driver. You should use a recent driver<br/>version and consider setting the `spring.jdbc.getParameterType.ignore` property to `true`(as a JVM system property or via the[`SpringProperties`](appendix.html#appendix-spring-properties) mechanism) if you encounter<br/>a performance issue (as reported on Oracle 12c, JBoss, and PostgreSQL).<br/><br/>Alternatively, you might consider specifying the corresponding JDBC types explicitly,<br/>either through a `BatchPreparedStatementSetter` (as shown earlier), through an explicit type<br/>array given to a `List<Object[]>` based call, through `registerSqlType` calls on a<br/>custom `MapSqlParameterSource` instance, or through a `BeanPropertySqlParameterSource`that derives the SQL type from the Java-declared property type even for a null value.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

#### [](#jdbc-batch-multi)3.5.3. Batch Operations with Multiple Batches ####

The preceding example of a batch update deals with batches that are so large that you want to
break them up into several smaller batches. You can do this with the methods
mentioned earlier by making multiple calls to the `batchUpdate` method, but there is now a
more convenient method. This method takes, in addition to the SQL statement, a`Collection` of objects that contain the parameters, the number of updates to make for each
batch, and a `ParameterizedPreparedStatementSetter` to set the values for the parameters
of the prepared statement. The framework loops over the provided values and breaks the
update calls into batches of the size specified.

The following example shows a batch update that uses a batch size of 100:

Java

```
public class JdbcActorDao implements ActorDao {

    private JdbcTemplate jdbcTemplate;

    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    public int[][] batchUpdate(final Collection<Actor> actors) {
        int[][] updateCounts = jdbcTemplate.batchUpdate(
                "update t_actor set first_name = ?, last_name = ? where id = ?",
                actors,
                100,
                (PreparedStatement ps, Actor actor) -> {
                    ps.setString(1, actor.getFirstName());
                    ps.setString(2, actor.getLastName());
                    ps.setLong(3, actor.getId().longValue());
                });
        return updateCounts;
    }

    // ... additional methods
}
```

Kotlin

```
class JdbcActorDao(dataSource: DataSource) : ActorDao {

    private val jdbcTemplate = JdbcTemplate(dataSource)

    fun batchUpdate(actors: List<Actor>): Array<IntArray> {
        return jdbcTemplate.batchUpdate(
                    "update t_actor set first_name = ?, last_name = ? where id = ?",
                    actors, 100) { ps, argument ->
            ps.setString(1, argument.firstName)
            ps.setString(2, argument.lastName)
            ps.setLong(3, argument.id)
        }
    }

    // ... additional methods
}
```

The batch update method for this call returns an array of `int` arrays that contains an
array entry for each batch with an array of the number of affected rows for each update.
The top-level array’s length indicates the number of batches run, and the second level
array’s length indicates the number of updates in that batch. The number of updates in
each batch should be the batch size provided for all batches (except that the last one
that might be less), depending on the total number of update objects provided. The update
count for each update statement is the one reported by the JDBC driver. If the count is
not available, the JDBC driver returns a value of `-2`.

### [](#jdbc-simple-jdbc)3.6. Simplifying JDBC Operations with the `SimpleJdbc` Classes ###

The `SimpleJdbcInsert` and `SimpleJdbcCall` classes provide a simplified configuration
by taking advantage of database metadata that can be retrieved through the JDBC driver.
This means that you have less to configure up front, although you can override or turn off
the metadata processing if you prefer to provide all the details in your code.

#### [](#jdbc-simple-jdbc-insert-1)3.6.1. Inserting Data by Using `SimpleJdbcInsert` ####

We start by looking at the `SimpleJdbcInsert` class with the minimal amount of
configuration options. You should instantiate the `SimpleJdbcInsert` in the data access
layer’s initialization method. For this example, the initializing method is the`setDataSource` method. You do not need to subclass the `SimpleJdbcInsert` class. Instead,
you can create a new instance and set the table name by using the `withTableName` method.
Configuration methods for this class follow the `fluid` style that returns the instance
of the `SimpleJdbcInsert`, which lets you chain all configuration methods. The following
example uses only one configuration method (we show examples of multiple methods later):

Java

```
public class JdbcActorDao implements ActorDao {

    private SimpleJdbcInsert insertActor;

    public void setDataSource(DataSource dataSource) {
        this.insertActor = new SimpleJdbcInsert(dataSource).withTableName("t_actor");
    }

    public void add(Actor actor) {
        Map<String, Object> parameters = new HashMap<String, Object>(3);
        parameters.put("id", actor.getId());
        parameters.put("first_name", actor.getFirstName());
        parameters.put("last_name", actor.getLastName());
        insertActor.execute(parameters);
    }

    // ... additional methods
}
```

Kotlin

```
class JdbcActorDao(dataSource: DataSource) : ActorDao {

    private val insertActor = SimpleJdbcInsert(dataSource).withTableName("t_actor")

    fun add(actor: Actor) {
        val parameters = mutableMapOf<String, Any>()
        parameters["id"] = actor.id
        parameters["first_name"] = actor.firstName
        parameters["last_name"] = actor.lastName
        insertActor.execute(parameters)
    }

    // ... additional methods
}
```

The `execute` method used here takes a plain `java.util.Map` as its only parameter. The
important thing to note here is that the keys used for the `Map` must match the column
names of the table, as defined in the database. This is because we read the metadata
to construct the actual insert statement.

#### [](#jdbc-simple-jdbc-insert-2)3.6.2. Retrieving Auto-generated Keys by Using `SimpleJdbcInsert` ####

The next example uses the same insert as the preceding example, but, instead of passing in the `id`, it
retrieves the auto-generated key and sets it on the new `Actor` object. When it creates
the `SimpleJdbcInsert`, in addition to specifying the table name, it specifies the name
of the generated key column with the `usingGeneratedKeyColumns` method. The following
listing shows how it works:

Java

```
public class JdbcActorDao implements ActorDao {

    private SimpleJdbcInsert insertActor;

    public void setDataSource(DataSource dataSource) {
        this.insertActor = new SimpleJdbcInsert(dataSource)
                .withTableName("t_actor")
                .usingGeneratedKeyColumns("id");
    }

    public void add(Actor actor) {
        Map<String, Object> parameters = new HashMap<String, Object>(2);
        parameters.put("first_name", actor.getFirstName());
        parameters.put("last_name", actor.getLastName());
        Number newId = insertActor.executeAndReturnKey(parameters);
        actor.setId(newId.longValue());
    }

    // ... additional methods
}
```

Kotlin

```
class JdbcActorDao(dataSource: DataSource) : ActorDao {

    private val insertActor = SimpleJdbcInsert(dataSource)
            .withTableName("t_actor").usingGeneratedKeyColumns("id")

    fun add(actor: Actor): Actor {
        val parameters = mapOf(
                "first_name" to actor.firstName,
                "last_name" to actor.lastName)
        val newId = insertActor.executeAndReturnKey(parameters);
        return actor.copy(id = newId.toLong())
    }

    // ... additional methods
}
```

The main difference when you run the insert by using this second approach is that you do not
add the `id` to the `Map`, and you call the `executeAndReturnKey` method. This returns a`java.lang.Number` object with which you can create an instance of the numerical type that
is used in your domain class. You cannot rely on all databases to return a specific Java
class here. `java.lang.Number` is the base class that you can rely on. If you have
multiple auto-generated columns or the generated values are non-numeric, you can
use a `KeyHolder` that is returned from the `executeAndReturnKeyHolder` method.

#### [](#jdbc-simple-jdbc-insert-3)3.6.3. Specifying Columns for a `SimpleJdbcInsert` ####

You can limit the columns for an insert by specifying a list of column names with the`usingColumns` method, as the following example shows:

Java

```
public class JdbcActorDao implements ActorDao {

    private SimpleJdbcInsert insertActor;

    public void setDataSource(DataSource dataSource) {
        this.insertActor = new SimpleJdbcInsert(dataSource)
                .withTableName("t_actor")
                .usingColumns("first_name", "last_name")
                .usingGeneratedKeyColumns("id");
    }

    public void add(Actor actor) {
        Map<String, Object> parameters = new HashMap<String, Object>(2);
        parameters.put("first_name", actor.getFirstName());
        parameters.put("last_name", actor.getLastName());
        Number newId = insertActor.executeAndReturnKey(parameters);
        actor.setId(newId.longValue());
    }

    // ... additional methods
}
```

Kotlin

```
class JdbcActorDao(dataSource: DataSource) : ActorDao {

    private val insertActor = SimpleJdbcInsert(dataSource)
            .withTableName("t_actor")
            .usingColumns("first_name", "last_name")
            .usingGeneratedKeyColumns("id")

    fun add(actor: Actor): Actor {
        val parameters = mapOf(
                "first_name" to actor.firstName,
                "last_name" to actor.lastName)
        val newId = insertActor.executeAndReturnKey(parameters);
        return actor.copy(id = newId.toLong())
    }

    // ... additional methods
}
```

The execution of the insert is the same as if you had relied on the metadata to determine
which columns to use.

#### [](#jdbc-simple-jdbc-parameters)3.6.4. Using `SqlParameterSource` to Provide Parameter Values ####

Using a `Map` to provide parameter values works fine, but it is not the most convenient
class to use. Spring provides a couple of implementations of the `SqlParameterSource`interface that you can use instead. The first one is `BeanPropertySqlParameterSource`,
which is a very convenient class if you have a JavaBean-compliant class that contains
your values. It uses the corresponding getter method to extract the parameter
values. The following example shows how to use `BeanPropertySqlParameterSource`:

Java

```
public class JdbcActorDao implements ActorDao {

    private SimpleJdbcInsert insertActor;

    public void setDataSource(DataSource dataSource) {
        this.insertActor = new SimpleJdbcInsert(dataSource)
                .withTableName("t_actor")
                .usingGeneratedKeyColumns("id");
    }

    public void add(Actor actor) {
        SqlParameterSource parameters = new BeanPropertySqlParameterSource(actor);
        Number newId = insertActor.executeAndReturnKey(parameters);
        actor.setId(newId.longValue());
    }

    // ... additional methods
}
```

Kotlin

```
class JdbcActorDao(dataSource: DataSource) : ActorDao {

    private val insertActor = SimpleJdbcInsert(dataSource)
            .withTableName("t_actor")
            .usingGeneratedKeyColumns("id")

    fun add(actor: Actor): Actor {
        val parameters = BeanPropertySqlParameterSource(actor)
        val newId = insertActor.executeAndReturnKey(parameters)
        return actor.copy(id = newId.toLong())
    }

    // ... additional methods
}
```

Another option is the `MapSqlParameterSource` that resembles a `Map` but provides a more
convenient `addValue` method that can be chained. The following example shows how to use it:

Java

```
public class JdbcActorDao implements ActorDao {

    private SimpleJdbcInsert insertActor;

    public void setDataSource(DataSource dataSource) {
        this.insertActor = new SimpleJdbcInsert(dataSource)
                .withTableName("t_actor")
                .usingGeneratedKeyColumns("id");
    }

    public void add(Actor actor) {
        SqlParameterSource parameters = new MapSqlParameterSource()
                .addValue("first_name", actor.getFirstName())
                .addValue("last_name", actor.getLastName());
        Number newId = insertActor.executeAndReturnKey(parameters);
        actor.setId(newId.longValue());
    }

    // ... additional methods
}
```

Kotlin

```
class JdbcActorDao(dataSource: DataSource) : ActorDao {

    private val insertActor = SimpleJdbcInsert(dataSource)
            .withTableName("t_actor")
            .usingGeneratedKeyColumns("id")

    fun add(actor: Actor): Actor {
        val parameters = MapSqlParameterSource()
                    .addValue("first_name", actor.firstName)
                    .addValue("last_name", actor.lastName)
        val newId = insertActor.executeAndReturnKey(parameters)
        return actor.copy(id = newId.toLong())
    }

    // ... additional methods
}
```

As you can see, the configuration is the same. Only the executing code has to change to
use these alternative input classes.

#### [](#jdbc-simple-jdbc-call-1)3.6.5. Calling a Stored Procedure with `SimpleJdbcCall` ####

The `SimpleJdbcCall` class uses metadata in the database to look up names of `in`and `out` parameters so that you do not have to explicitly declare them. You can
declare parameters if you prefer to do that or if you have parameters (such as `ARRAY`or `STRUCT`) that do not have an automatic mapping to a Java class. The first example
shows a simple procedure that returns only scalar values in `VARCHAR` and `DATE` format
from a MySQL database. The example procedure reads a specified actor entry and returns`first_name`, `last_name`, and `birth_date` columns in the form of `out` parameters.
The following listing shows the first example:

```
CREATE PROCEDURE read_actor (
    IN in_id INTEGER,
    OUT out_first_name VARCHAR(100),
    OUT out_last_name VARCHAR(100),
    OUT out_birth_date DATE)
BEGIN
    SELECT first_name, last_name, birth_date
    INTO out_first_name, out_last_name, out_birth_date
    FROM t_actor where id = in_id;
END;
```

The `in_id` parameter contains the `id` of the actor that you are looking up. The `out`parameters return the data read from the table.

You can declare `SimpleJdbcCall` in a manner similar to declaring `SimpleJdbcInsert`. You
should instantiate and configure the class in the initialization method of your data-access
layer. Compared to the `StoredProcedure` class, you need not create a subclass
and you need not to declare parameters that can be looked up in the database metadata.
The following example of a `SimpleJdbcCall` configuration uses the preceding stored
procedure (the only configuration option, in addition to the `DataSource`, is the name
of the stored procedure):

Java

```
public class JdbcActorDao implements ActorDao {

    private SimpleJdbcCall procReadActor;

    public void setDataSource(DataSource dataSource) {
        this.procReadActor = new SimpleJdbcCall(dataSource)
                .withProcedureName("read_actor");
    }

    public Actor readActor(Long id) {
        SqlParameterSource in = new MapSqlParameterSource()
                .addValue("in_id", id);
        Map out = procReadActor.execute(in);
        Actor actor = new Actor();
        actor.setId(id);
        actor.setFirstName((String) out.get("out_first_name"));
        actor.setLastName((String) out.get("out_last_name"));
        actor.setBirthDate((Date) out.get("out_birth_date"));
        return actor;
    }

    // ... additional methods
}
```

Kotlin

```
class JdbcActorDao(dataSource: DataSource) : ActorDao {

    private val procReadActor = SimpleJdbcCall(dataSource)
            .withProcedureName("read_actor")

    fun readActor(id: Long): Actor {
        val source = MapSqlParameterSource().addValue("in_id", id)
        val output = procReadActor.execute(source)
        return Actor(
                id,
                output["out_first_name"] as String,
                output["out_last_name"] as String,
                output["out_birth_date"] as Date)
    }

        // ... additional methods
}
```

The code you write for the execution of the call involves creating an `SqlParameterSource`containing the IN parameter. You must match the name provided for the input value
with that of the parameter name declared in the stored procedure. The case does not have
to match because you use metadata to determine how database objects should be referred to
in a stored procedure. What is specified in the source for the stored procedure is not
necessarily the way it is stored in the database. Some databases transform names to all
upper case, while others use lower case or use the case as specified.

The `execute` method takes the IN parameters and returns a `Map` that contains any `out`parameters keyed by the name, as specified in the stored procedure. In this case, they are`out_first_name`, `out_last_name`, and `out_birth_date`.

The last part of the `execute` method creates an `Actor` instance to use to return the
data retrieved. Again, it is important to use the names of the `out` parameters as they
are declared in the stored procedure. Also, the case in the names of the `out`parameters stored in the results map matches that of the `out` parameter names in the
database, which could vary between databases. To make your code more portable, you should
do a case-insensitive lookup or instruct Spring to use a `LinkedCaseInsensitiveMap`.
To do the latter, you can create your own `JdbcTemplate` and set the `setResultsMapCaseInsensitive`property to `true`. Then you can pass this customized `JdbcTemplate` instance into
the constructor of your `SimpleJdbcCall`. The following example shows this configuration:

Java

```
public class JdbcActorDao implements ActorDao {

    private SimpleJdbcCall procReadActor;

    public void setDataSource(DataSource dataSource) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        jdbcTemplate.setResultsMapCaseInsensitive(true);
        this.procReadActor = new SimpleJdbcCall(jdbcTemplate)
                .withProcedureName("read_actor");
    }

    // ... additional methods
}
```

Kotlin

```
class JdbcActorDao(dataSource: DataSource) : ActorDao {

    private var procReadActor = SimpleJdbcCall(JdbcTemplate(dataSource).apply {
        isResultsMapCaseInsensitive = true
    }).withProcedureName("read_actor")

    // ... additional methods
}
```

By taking this action, you avoid conflicts in the case used for the names of your
returned `out` parameters.

#### [](#jdbc-simple-jdbc-call-2)3.6.6. Explicitly Declaring Parameters to Use for a `SimpleJdbcCall` ####

Earlier in this chapter, we described how parameters are deduced from metadata, but you can declare them
explicitly if you wish. You can do so by creating and configuring `SimpleJdbcCall` with
the `declareParameters` method, which takes a variable number of `SqlParameter` objects
as input. See the [next section](#jdbc-params) for details on how to define an `SqlParameter`.

|   |Explicit declarations are necessary if the database you use is not a Spring-supported<br/>database. Currently, Spring supports metadata lookup of stored procedure calls for the<br/>following databases: Apache Derby, DB2, MySQL, Microsoft SQL Server, Oracle, and Sybase.<br/>We also support metadata lookup of stored functions for MySQL, Microsoft SQL Server,<br/>and Oracle.|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

You can opt to explicitly declare one, some, or all of the parameters. The parameter
metadata is still used where you do not explicitly declare parameters. To bypass all
processing of metadata lookups for potential parameters and use only the declared
parameters, you can call the method `withoutProcedureColumnMetaDataAccess` as part of the
declaration. Suppose that you have two or more different call signatures declared for a
database function. In this case, you call `useInParameterNames` to specify the list
of IN parameter names to include for a given signature.

The following example shows a fully declared procedure call and uses the information from
the preceding example:

Java

```
public class JdbcActorDao implements ActorDao {

    private SimpleJdbcCall procReadActor;

    public void setDataSource(DataSource dataSource) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        jdbcTemplate.setResultsMapCaseInsensitive(true);
        this.procReadActor = new SimpleJdbcCall(jdbcTemplate)
                .withProcedureName("read_actor")
                .withoutProcedureColumnMetaDataAccess()
                .useInParameterNames("in_id")
                .declareParameters(
                        new SqlParameter("in_id", Types.NUMERIC),
                        new SqlOutParameter("out_first_name", Types.VARCHAR),
                        new SqlOutParameter("out_last_name", Types.VARCHAR),
                        new SqlOutParameter("out_birth_date", Types.DATE)
                );
    }

    // ... additional methods
}
```

Kotlin

```
class JdbcActorDao(dataSource: DataSource) : ActorDao {

        private val procReadActor = SimpleJdbcCall(JdbcTemplate(dataSource).apply {
            isResultsMapCaseInsensitive = true
        }).withProcedureName("read_actor")
                .withoutProcedureColumnMetaDataAccess()
                .useInParameterNames("in_id")
                .declareParameters(
                        SqlParameter("in_id", Types.NUMERIC),
                        SqlOutParameter("out_first_name", Types.VARCHAR),
                        SqlOutParameter("out_last_name", Types.VARCHAR),
                        SqlOutParameter("out_birth_date", Types.DATE)
    )

        // ... additional methods
}
```

The execution and end results of the two examples are the same. The second example specifies all
details explicitly rather than relying on metadata.

#### [](#jdbc-params)3.6.7. How to Define `SqlParameters` ####

To define a parameter for the `SimpleJdbc` classes and also for the RDBMS operations
classes (covered in [Modeling JDBC Operations as Java Objects](#jdbc-object)) you can use `SqlParameter` or one of its subclasses.
To do so, you typically specify the parameter name and SQL type in the constructor. The SQL type
is specified by using the `java.sql.Types` constants. Earlier in this chapter, we saw declarations
similar to the following:

Java

```
new SqlParameter("in_id", Types.NUMERIC),
new SqlOutParameter("out_first_name", Types.VARCHAR),
```

Kotlin

```
SqlParameter("in_id", Types.NUMERIC),
SqlOutParameter("out_first_name", Types.VARCHAR),
```

The first line with the `SqlParameter` declares an IN parameter. You can use IN parameters
for both stored procedure calls and for queries by using the `SqlQuery` and its
subclasses (covered in [Understanding `SqlQuery`](#jdbc-SqlQuery)).

The second line (with the `SqlOutParameter`) declares an `out` parameter to be used in a
stored procedure call. There is also an `SqlInOutParameter` for `InOut` parameters
(parameters that provide an IN value to the procedure and that also return a value).

|   |Only parameters declared as `SqlParameter` and `SqlInOutParameter` are used to<br/>provide input values. This is different from the `StoredProcedure` class, which (for<br/>backwards compatibility reasons) lets input values be provided for parameters<br/>declared as `SqlOutParameter`.|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

For IN parameters, in addition to the name and the SQL type, you can specify a scale for
numeric data or a type name for custom database types. For `out` parameters, you can
provide a `RowMapper` to handle mapping of rows returned from a `REF` cursor. Another
option is to specify an `SqlReturnType` that provides an opportunity to define
customized handling of the return values.

#### [](#jdbc-simple-jdbc-call-3)3.6.8. Calling a Stored Function by Using `SimpleJdbcCall` ####

You can call a stored function in almost the same way as you call a stored procedure, except
that you provide a function name rather than a procedure name. You use the`withFunctionName` method as part of the configuration to indicate that you want to make
a call to a function, and the corresponding string for a function call is generated. A
specialized call (`executeFunction`) is used to run the function, and it
returns the function return value as an object of a specified type, which means you do
not have to retrieve the return value from the results map. A similar convenience method
(named `executeObject`) is also available for stored procedures that have only one `out`parameter. The following example (for MySQL) is based on a stored function named `get_actor_name`that returns an actor’s full name:

```
CREATE FUNCTION get_actor_name (in_id INTEGER)
RETURNS VARCHAR(200) READS SQL DATA
BEGIN
    DECLARE out_name VARCHAR(200);
    SELECT concat(first_name, ' ', last_name)
        INTO out_name
        FROM t_actor where id = in_id;
    RETURN out_name;
END;
```

To call this function, we again create a `SimpleJdbcCall` in the initialization method,
as the following example shows:

Java

```
public class JdbcActorDao implements ActorDao {

    private SimpleJdbcCall funcGetActorName;

    public void setDataSource(DataSource dataSource) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        jdbcTemplate.setResultsMapCaseInsensitive(true);
        this.funcGetActorName = new SimpleJdbcCall(jdbcTemplate)
                .withFunctionName("get_actor_name");
    }

    public String getActorName(Long id) {
        SqlParameterSource in = new MapSqlParameterSource()
                .addValue("in_id", id);
        String name = funcGetActorName.executeFunction(String.class, in);
        return name;
    }

    // ... additional methods
}
```

Kotlin

```
class JdbcActorDao(dataSource: DataSource) : ActorDao {

    private val jdbcTemplate = JdbcTemplate(dataSource).apply {
        isResultsMapCaseInsensitive = true
    }
    private val funcGetActorName = SimpleJdbcCall(jdbcTemplate)
            .withFunctionName("get_actor_name")

    fun getActorName(id: Long): String {
        val source = MapSqlParameterSource().addValue("in_id", id)
        return funcGetActorName.executeFunction(String::class.java, source)
    }

    // ... additional methods
}
```

The `executeFunction` method used returns a `String` that contains the return value from the
function call.

#### [](#jdbc-simple-jdbc-call-4)3.6.9. Returning a `ResultSet` or REF Cursor from a `SimpleJdbcCall` ####

Calling a stored procedure or function that returns a result set is a bit tricky. Some
databases return result sets during the JDBC results processing, while others require an
explicitly registered `out` parameter of a specific type. Both approaches need
additional processing to loop over the result set and process the returned rows. With
the `SimpleJdbcCall`, you can use the `returningResultSet` method and declare a `RowMapper`implementation to be used for a specific parameter. If the result set is
returned during the results processing, there are no names defined, so the returned
results must match the order in which you declare the `RowMapper`implementations. The name specified is still used to store the processed list of results
in the results map that is returned from the `execute` statement.

The next example (for MySQL) uses a stored procedure that takes no IN parameters and returns
all rows from the `t_actor` table:

```
CREATE PROCEDURE read_all_actors()
BEGIN
 SELECT a.id, a.first_name, a.last_name, a.birth_date FROM t_actor a;
END;
```

To call this procedure, you can declare the `RowMapper`. Because the class to which you want
to map follows the JavaBean rules, you can use a `BeanPropertyRowMapper` that is created by
passing in the required class to map to in the `newInstance` method.
The following example shows how to do so:

Java

```
public class JdbcActorDao implements ActorDao {

    private SimpleJdbcCall procReadAllActors;

    public void setDataSource(DataSource dataSource) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        jdbcTemplate.setResultsMapCaseInsensitive(true);
        this.procReadAllActors = new SimpleJdbcCall(jdbcTemplate)
                .withProcedureName("read_all_actors")
                .returningResultSet("actors",
                BeanPropertyRowMapper.newInstance(Actor.class));
    }

    public List getActorsList() {
        Map m = procReadAllActors.execute(new HashMap<String, Object>(0));
        return (List) m.get("actors");
    }

    // ... additional methods
}
```

Kotlin

```
class JdbcActorDao(dataSource: DataSource) : ActorDao {

        private val procReadAllActors = SimpleJdbcCall(JdbcTemplate(dataSource).apply {
            isResultsMapCaseInsensitive = true
        }).withProcedureName("read_all_actors")
                .returningResultSet("actors",
                        BeanPropertyRowMapper.newInstance(Actor::class.java))

    fun getActorsList(): List<Actor> {
        val m = procReadAllActors.execute(mapOf<String, Any>())
        return m["actors"] as List<Actor>
    }

    // ... additional methods
}
```

The `execute` call passes in an empty `Map`, because this call does not take any parameters.
The list of actors is then retrieved from the results map and returned to the caller.

### [](#jdbc-object)3.7. Modeling JDBC Operations as Java Objects ###

The `org.springframework.jdbc.object` package contains classes that let you access
the database in a more object-oriented manner. As an example, you can run queries
and get the results back as a list that contains business objects with the relational
column data mapped to the properties of the business object. You can also run stored
procedures and run update, delete, and insert statements.

|   |Many Spring developers believe that the various RDBMS operation classes described below<br/>(with the exception of the [`StoredProcedure`](#jdbc-StoredProcedure) class) can often<br/>be replaced with straight `JdbcTemplate` calls. Often, it is simpler to write a DAO<br/>method that calls a method on a `JdbcTemplate` directly (as opposed to<br/>encapsulating a query as a full-blown class).<br/><br/>However, if you are getting measurable value from using the RDBMS operation classes,<br/>you should continue to use these classes.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

#### [](#jdbc-SqlQuery)3.7.1. Understanding `SqlQuery` ####

`SqlQuery` is a reusable, thread-safe class that encapsulates an SQL query. Subclasses
must implement the `newRowMapper(..)` method to provide a `RowMapper` instance that can
create one object per row obtained from iterating over the `ResultSet` that is created
during the execution of the query. The `SqlQuery` class is rarely used directly, because
the `MappingSqlQuery` subclass provides a much more convenient implementation for
mapping rows to Java classes. Other implementations that extend `SqlQuery` are`MappingSqlQueryWithParameters` and `UpdatableSqlQuery`.

#### [](#jdbc-MappingSqlQuery)3.7.2. Using `MappingSqlQuery` ####

`MappingSqlQuery` is a reusable query in which concrete subclasses must implement the
abstract `mapRow(..)` method to convert each row of the supplied `ResultSet` into an
object of the type specified. The following example shows a custom query that maps the
data from the `t_actor` relation to an instance of the `Actor` class:

Java

```
public class ActorMappingQuery extends MappingSqlQuery<Actor> {

    public ActorMappingQuery(DataSource ds) {
        super(ds, "select id, first_name, last_name from t_actor where id = ?");
        declareParameter(new SqlParameter("id", Types.INTEGER));
        compile();
    }

    @Override
    protected Actor mapRow(ResultSet rs, int rowNumber) throws SQLException {
        Actor actor = new Actor();
        actor.setId(rs.getLong("id"));
        actor.setFirstName(rs.getString("first_name"));
        actor.setLastName(rs.getString("last_name"));
        return actor;
    }
}
```

Kotlin

```
class ActorMappingQuery(ds: DataSource) : MappingSqlQuery<Actor>(ds, "select id, first_name, last_name from t_actor where id = ?") {

    init {
        declareParameter(SqlParameter("id", Types.INTEGER))
        compile()
    }

    override fun mapRow(rs: ResultSet, rowNumber: Int) = Actor(
            rs.getLong("id"),
            rs.getString("first_name"),
            rs.getString("last_name")
    )
}
```

The class extends `MappingSqlQuery` parameterized with the `Actor` type. The constructor
for this customer query takes a `DataSource` as the only parameter. In this
constructor, you can call the constructor on the superclass with the `DataSource` and the SQL
that should be run to retrieve the rows for this query. This SQL is used to
create a `PreparedStatement`, so it may contain placeholders for any parameters to be
passed in during execution. You must declare each parameter by using the `declareParameter`method passing in an `SqlParameter`. The `SqlParameter` takes a name, and the JDBC type
as defined in `java.sql.Types`. After you define all parameters, you can call the`compile()` method so that the statement can be prepared and later run. This class is
thread-safe after it is compiled, so, as long as these instances are created when the DAO
is initialized, they can be kept as instance variables and be reused. The following
example shows how to define such a class:

Java

```
private ActorMappingQuery actorMappingQuery;

@Autowired
public void setDataSource(DataSource dataSource) {
    this.actorMappingQuery = new ActorMappingQuery(dataSource);
}

public Customer getCustomer(Long id) {
    return actorMappingQuery.findObject(id);
}
```

Kotlin

```
private val actorMappingQuery = ActorMappingQuery(dataSource)

fun getCustomer(id: Long) = actorMappingQuery.findObject(id)
```

The method in the preceding example retrieves the customer with the `id` that is passed in as the
only parameter. Since we want only one object to be returned, we call the `findObject` convenience
method with the `id` as the parameter. If we had instead a query that returned a
list of objects and took additional parameters, we would use one of the `execute`methods that takes an array of parameter values passed in as varargs. The following
example shows such a method:

Java

```
public List<Actor> searchForActors(int age, String namePattern) {
    List<Actor> actors = actorSearchMappingQuery.execute(age, namePattern);
    return actors;
}
```

Kotlin

```
fun searchForActors(age: Int, namePattern: String) =
            actorSearchMappingQuery.execute(age, namePattern)
```

#### [](#jdbc-SqlUpdate)3.7.3. Using `SqlUpdate` ####

The `SqlUpdate` class encapsulates an SQL update. As with a query, an update object is
reusable, and, as with all `RdbmsOperation` classes, an update can have parameters and is
defined in SQL. This class provides a number of `update(..)` methods analogous to the`execute(..)` methods of query objects. The `SqlUpdate` class is concrete. It can be
subclassed — for example, to add a custom update method.
However, you do not have to subclass the `SqlUpdate`class, since it can easily be parameterized by setting SQL and declaring parameters.
The following example creates a custom update method named `execute`:

Java

```
import java.sql.Types;
import javax.sql.DataSource;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.object.SqlUpdate;

public class UpdateCreditRating extends SqlUpdate {

    public UpdateCreditRating(DataSource ds) {
        setDataSource(ds);
        setSql("update customer set credit_rating = ? where id = ?");
        declareParameter(new SqlParameter("creditRating", Types.NUMERIC));
        declareParameter(new SqlParameter("id", Types.NUMERIC));
        compile();
    }

    /**
     * @param id for the Customer to be updated
     * @param rating the new value for credit rating
     * @return number of rows updated
     */
    public int execute(int id, int rating) {
        return update(rating, id);
    }
}
```

Kotlin

```
import java.sql.Types
import javax.sql.DataSource
import org.springframework.jdbc.core.SqlParameter
import org.springframework.jdbc.object.SqlUpdate

class UpdateCreditRating(ds: DataSource) : SqlUpdate() {

    init {
        setDataSource(ds)
        sql = "update customer set credit_rating = ? where id = ?"
        declareParameter(SqlParameter("creditRating", Types.NUMERIC))
        declareParameter(SqlParameter("id", Types.NUMERIC))
        compile()
    }

    /**
     * @param id for the Customer to be updated
     * @param rating the new value for credit rating
     * @return number of rows updated
     */
    fun execute(id: Int, rating: Int): Int {
        return update(rating, id)
    }
}
```

#### [](#jdbc-StoredProcedure)3.7.4. Using `StoredProcedure` ####

The `StoredProcedure` class is an `abstract` superclass for object abstractions of RDBMS
stored procedures.

The inherited `sql` property is the name of the stored procedure in the RDBMS.

To define a parameter for the `StoredProcedure` class, you can use an `SqlParameter` or one
of its subclasses. You must specify the parameter name and SQL type in the constructor,
as the following code snippet shows:

Java

```
new SqlParameter("in_id", Types.NUMERIC),
new SqlOutParameter("out_first_name", Types.VARCHAR),
```

Kotlin

```
SqlParameter("in_id", Types.NUMERIC),
SqlOutParameter("out_first_name", Types.VARCHAR),
```

The SQL type is specified using the `java.sql.Types` constants.

The first line (with the `SqlParameter`) declares an IN parameter. You can use IN parameters
both for stored procedure calls and for queries using the `SqlQuery` and its
subclasses (covered in [Understanding `SqlQuery`](#jdbc-SqlQuery)).

The second line (with the `SqlOutParameter`) declares an `out` parameter to be used in the
stored procedure call. There is also an `SqlInOutParameter` for `InOut` parameters
(parameters that provide an `in` value to the procedure and that also return a value).

For `in` parameters, in addition to the name and the SQL type, you can specify a
scale for numeric data or a type name for custom database types. For `out` parameters,
you can provide a `RowMapper` to handle mapping of rows returned from a `REF` cursor.
Another option is to specify an `SqlReturnType` that lets you define customized
handling of the return values.

The next example of a simple DAO uses a `StoredProcedure` to call a function
(`sysdate()`), which comes with any Oracle database. To use the stored procedure
functionality, you have to create a class that extends `StoredProcedure`. In this
example, the `StoredProcedure` class is an inner class. However, if you need to reuse the`StoredProcedure`, you can declare it as a top-level class. This example has no input
parameters, but an output parameter is declared as a date type by using the`SqlOutParameter` class. The `execute()` method runs the procedure and extracts the
returned date from the results `Map`. The results `Map` has an entry for each declared
output parameter (in this case, only one) by using the parameter name as the key.
The following listing shows our custom StoredProcedure class:

Java

```
import java.sql.Types;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.object.StoredProcedure;

public class StoredProcedureDao {

    private GetSysdateProcedure getSysdate;

    @Autowired
    public void init(DataSource dataSource) {
        this.getSysdate = new GetSysdateProcedure(dataSource);
    }

    public Date getSysdate() {
        return getSysdate.execute();
    }

    private class GetSysdateProcedure extends StoredProcedure {

        private static final String SQL = "sysdate";

        public GetSysdateProcedure(DataSource dataSource) {
            setDataSource(dataSource);
            setFunction(true);
            setSql(SQL);
            declareParameter(new SqlOutParameter("date", Types.DATE));
            compile();
        }

        public Date execute() {
            // the 'sysdate' sproc has no input parameters, so an empty Map is supplied...
            Map<String, Object> results = execute(new HashMap<String, Object>());
            Date sysdate = (Date) results.get("date");
            return sysdate;
        }
    }

}
```

Kotlin

```
import java.sql.Types
import java.util.Date
import java.util.Map
import javax.sql.DataSource
import org.springframework.jdbc.core.SqlOutParameter
import org.springframework.jdbc.object.StoredProcedure

class StoredProcedureDao(dataSource: DataSource) {

    private val SQL = "sysdate"

    private val getSysdate = GetSysdateProcedure(dataSource)

    val sysdate: Date
        get() = getSysdate.execute()

    private inner class GetSysdateProcedure(dataSource: DataSource) : StoredProcedure() {

        init {
            setDataSource(dataSource)
            isFunction = true
            sql = SQL
            declareParameter(SqlOutParameter("date", Types.DATE))
            compile()
        }

        fun execute(): Date {
            // the 'sysdate' sproc has no input parameters, so an empty Map is supplied...
            val results = execute(mutableMapOf<String, Any>())
            return results["date"] as Date
        }
    }
}
```

The following example of a `StoredProcedure` has two output parameters (in this case,
Oracle REF cursors):

Java

```
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import oracle.jdbc.OracleTypes;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.object.StoredProcedure;

public class TitlesAndGenresStoredProcedure extends StoredProcedure {

    private static final String SPROC_NAME = "AllTitlesAndGenres";

    public TitlesAndGenresStoredProcedure(DataSource dataSource) {
        super(dataSource, SPROC_NAME);
        declareParameter(new SqlOutParameter("titles", OracleTypes.CURSOR, new TitleMapper()));
        declareParameter(new SqlOutParameter("genres", OracleTypes.CURSOR, new GenreMapper()));
        compile();
    }

    public Map<String, Object> execute() {
        // again, this sproc has no input parameters, so an empty Map is supplied
        return super.execute(new HashMap<String, Object>());
    }
}
```

Kotlin

```
import java.util.HashMap
import javax.sql.DataSource
import oracle.jdbc.OracleTypes
import org.springframework.jdbc.core.SqlOutParameter
import org.springframework.jdbc.object.StoredProcedure

class TitlesAndGenresStoredProcedure(dataSource: DataSource) : StoredProcedure(dataSource, SPROC_NAME) {

    companion object {
        private const val SPROC_NAME = "AllTitlesAndGenres"
    }

    init {
        declareParameter(SqlOutParameter("titles", OracleTypes.CURSOR, TitleMapper()))
        declareParameter(SqlOutParameter("genres", OracleTypes.CURSOR, GenreMapper()))
        compile()
    }

    fun execute(): Map<String, Any> {
        // again, this sproc has no input parameters, so an empty Map is supplied
        return super.execute(HashMap<String, Any>())
    }
}
```

Notice how the overloaded variants of the `declareParameter(..)` method that have been
used in the `TitlesAndGenresStoredProcedure` constructor are passed `RowMapper`implementation instances. This is a very convenient and powerful way to reuse existing
functionality. The next two examples provide code for the two `RowMapper` implementations.

The `TitleMapper` class maps a `ResultSet` to a `Title` domain object for each row in
the supplied `ResultSet`, as follows:

Java

```
import java.sql.ResultSet;
import java.sql.SQLException;
import com.foo.domain.Title;
import org.springframework.jdbc.core.RowMapper;

public final class TitleMapper implements RowMapper<Title> {

    public Title mapRow(ResultSet rs, int rowNum) throws SQLException {
        Title title = new Title();
        title.setId(rs.getLong("id"));
        title.setName(rs.getString("name"));
        return title;
    }
}
```

Kotlin

```
import java.sql.ResultSet
import com.foo.domain.Title
import org.springframework.jdbc.core.RowMapper

class TitleMapper : RowMapper<Title> {

    override fun mapRow(rs: ResultSet, rowNum: Int) =
            Title(rs.getLong("id"), rs.getString("name"))
}
```

The `GenreMapper` class maps a `ResultSet` to a `Genre` domain object for each row in
the supplied `ResultSet`, as follows:

Java

```
import java.sql.ResultSet;
import java.sql.SQLException;
import com.foo.domain.Genre;
import org.springframework.jdbc.core.RowMapper;

public final class GenreMapper implements RowMapper<Genre> {

    public Genre mapRow(ResultSet rs, int rowNum) throws SQLException {
        return new Genre(rs.getString("name"));
    }
}
```

Kotlin

```
import java.sql.ResultSet
import com.foo.domain.Genre
import org.springframework.jdbc.core.RowMapper

class GenreMapper : RowMapper<Genre> {

    override fun mapRow(rs: ResultSet, rowNum: Int): Genre {
        return Genre(rs.getString("name"))
    }
}
```

To pass parameters to a stored procedure that has one or more input parameters in its
definition in the RDBMS, you can code a strongly typed `execute(..)` method that would
delegate to the untyped `execute(Map)` method in the superclass, as the following example shows:

Java

```
import java.sql.Types;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import oracle.jdbc.OracleTypes;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.object.StoredProcedure;

public class TitlesAfterDateStoredProcedure extends StoredProcedure {

    private static final String SPROC_NAME = "TitlesAfterDate";
    private static final String CUTOFF_DATE_PARAM = "cutoffDate";

    public TitlesAfterDateStoredProcedure(DataSource dataSource) {
        super(dataSource, SPROC_NAME);
        declareParameter(new SqlParameter(CUTOFF_DATE_PARAM, Types.DATE);
        declareParameter(new SqlOutParameter("titles", OracleTypes.CURSOR, new TitleMapper()));
        compile();
    }

    public Map<String, Object> execute(Date cutoffDate) {
        Map<String, Object> inputs = new HashMap<String, Object>();
        inputs.put(CUTOFF_DATE_PARAM, cutoffDate);
        return super.execute(inputs);
    }
}
```

Kotlin

```
import java.sql.Types
import java.util.Date
import javax.sql.DataSource
import oracle.jdbc.OracleTypes
import org.springframework.jdbc.core.SqlOutParameter
import org.springframework.jdbc.core.SqlParameter
import org.springframework.jdbc.object.StoredProcedure

class TitlesAfterDateStoredProcedure(dataSource: DataSource) : StoredProcedure(dataSource, SPROC_NAME) {

    companion object {
        private const val SPROC_NAME = "TitlesAfterDate"
        private const val CUTOFF_DATE_PARAM = "cutoffDate"
    }

    init {
        declareParameter(SqlParameter(CUTOFF_DATE_PARAM, Types.DATE))
        declareParameter(SqlOutParameter("titles", OracleTypes.CURSOR, TitleMapper()))
        compile()
    }

    fun execute(cutoffDate: Date) = super.execute(
            mapOf<String, Any>(CUTOFF_DATE_PARAM to cutoffDate))
}
```

### [](#jdbc-parameter-handling)3.8. Common Problems with Parameter and Data Value Handling ###

Common problems with parameters and data values exist in the different approaches
provided by Spring Framework’s JDBC support. This section covers how to address them.

#### [](#jdbc-type-information)3.8.1. Providing SQL Type Information for Parameters ####

Usually, Spring determines the SQL type of the parameters based on the type of parameter
passed in. It is possible to explicitly provide the SQL type to be used when setting
parameter values. This is sometimes necessary to correctly set `NULL` values.

You can provide SQL type information in several ways:

* Many update and query methods of the `JdbcTemplate` take an additional parameter in
  the form of an `int` array. This array is used to indicate the SQL type of the
  corresponding parameter by using constant values from the `java.sql.Types` class. Provide
  one entry for each parameter.

* You can use the `SqlParameterValue` class to wrap the parameter value that needs this
  additional information. To do so, create a new instance for each value and pass in the SQL type
  and the parameter value in the constructor. You can also provide an optional scale
  parameter for numeric values.

* For methods that work with named parameters, you can use the `SqlParameterSource` classes,`BeanPropertySqlParameterSource` or `MapSqlParameterSource`. They both have methods
  for registering the SQL type for any of the named parameter values.

#### [](#jdbc-lob)3.8.2. Handling BLOB and CLOB objects ####

You can store images, other binary data, and large chunks of text in the database. These
large objects are called BLOBs (Binary Large OBject) for binary data and CLOBs (Character
Large OBject) for character data. In Spring, you can handle these large objects by using
the `JdbcTemplate` directly and also when using the higher abstractions provided by RDBMS
Objects and the `SimpleJdbc` classes. All of these approaches use an implementation of
the `LobHandler` interface for the actual management of the LOB (Large OBject) data.`LobHandler` provides access to a `LobCreator` class, through the `getLobCreator` method,
that is used for creating new LOB objects to be inserted.

`LobCreator` and `LobHandler` provide the following support for LOB input and output:

* BLOB

  * `byte[]`: `getBlobAsBytes` and `setBlobAsBytes`

  * `InputStream`: `getBlobAsBinaryStream` and `setBlobAsBinaryStream`

* CLOB

  * `String`: `getClobAsString` and `setClobAsString`

  * `InputStream`: `getClobAsAsciiStream` and `setClobAsAsciiStream`

  * `Reader`: `getClobAsCharacterStream` and `setClobAsCharacterStream`

The next example shows how to create and insert a BLOB. Later we show how to read
it back from the database.

This example uses a `JdbcTemplate` and an implementation of the`AbstractLobCreatingPreparedStatementCallback`. It implements one method,`setValues`. This method provides a `LobCreator` that we use to set the values for the
LOB columns in your SQL insert statement.

For this example, we assume that there is a variable, `lobHandler`, that is already
set to an instance of a `DefaultLobHandler`. You typically set this value through
dependency injection.

The following example shows how to create and insert a BLOB:

Java

```
final File blobIn = new File("spring2004.jpg");
final InputStream blobIs = new FileInputStream(blobIn);
final File clobIn = new File("large.txt");
final InputStream clobIs = new FileInputStream(clobIn);
final InputStreamReader clobReader = new InputStreamReader(clobIs);

jdbcTemplate.execute(
    "INSERT INTO lob_table (id, a_clob, a_blob) VALUES (?, ?, ?)",
    new AbstractLobCreatingPreparedStatementCallback(lobHandler) {  (1)
        protected void setValues(PreparedStatement ps, LobCreator lobCreator) throws SQLException {
            ps.setLong(1, 1L);
            lobCreator.setClobAsCharacterStream(ps, 2, clobReader, (int)clobIn.length());  (2)
            lobCreator.setBlobAsBinaryStream(ps, 3, blobIs, (int)blobIn.length());  (3)
        }
    }
);

blobIs.close();
clobReader.close();
```

|**1**|Pass in the `lobHandler` that (in this example) is a plain `DefaultLobHandler`. |
|-----|--------------------------------------------------------------------------------|
|**2**|Using the method `setClobAsCharacterStream` to pass in the contents of the CLOB.|
|**3**| Using the method `setBlobAsBinaryStream` to pass in the contents of the BLOB.  |

Kotlin

```
val blobIn = File("spring2004.jpg")
val blobIs = FileInputStream(blobIn)
val clobIn = File("large.txt")
val clobIs = FileInputStream(clobIn)
val clobReader = InputStreamReader(clobIs)

jdbcTemplate.execute(
        "INSERT INTO lob_table (id, a_clob, a_blob) VALUES (?, ?, ?)",
        object: AbstractLobCreatingPreparedStatementCallback(lobHandler) {  (1)
            override fun setValues(ps: PreparedStatement, lobCreator: LobCreator) {
                ps.setLong(1, 1L)
                lobCreator.setClobAsCharacterStream(ps, 2, clobReader, clobIn.length().toInt())  (2)
                lobCreator.setBlobAsBinaryStream(ps, 3, blobIs, blobIn.length().toInt())  (3)
            }
        }
)
blobIs.close()
clobReader.close()
```

|**1**|Pass in the `lobHandler` that (in this example) is a plain `DefaultLobHandler`. |
|-----|--------------------------------------------------------------------------------|
|**2**|Using the method `setClobAsCharacterStream` to pass in the contents of the CLOB.|
|**3**| Using the method `setBlobAsBinaryStream` to pass in the contents of the BLOB.  |

|   |If you invoke the `setBlobAsBinaryStream`, `setClobAsAsciiStream`, or`setClobAsCharacterStream` method on the `LobCreator` returned from`DefaultLobHandler.getLobCreator()`, you can optionally specify a negative value for the`contentLength` argument. If the specified content length is negative, the`DefaultLobHandler` uses the JDBC 4.0 variants of the set-stream methods without a<br/>length parameter. Otherwise, it passes the specified length on to the driver.<br/><br/>See the documentation for the JDBC driver you use to verify that it supports streaming a<br/>LOB without providing the content length.|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

Now it is time to read the LOB data from the database. Again, you use a `JdbcTemplate`with the same instance variable `lobHandler` and a reference to a `DefaultLobHandler`.
The following example shows how to do so:

Java

```
List<Map<String, Object>> l = jdbcTemplate.query("select id, a_clob, a_blob from lob_table",
    new RowMapper<Map<String, Object>>() {
        public Map<String, Object> mapRow(ResultSet rs, int i) throws SQLException {
            Map<String, Object> results = new HashMap<String, Object>();
            String clobText = lobHandler.getClobAsString(rs, "a_clob");  (1)
            results.put("CLOB", clobText);
            byte[] blobBytes = lobHandler.getBlobAsBytes(rs, "a_blob");  (2)
            results.put("BLOB", blobBytes);
            return results;
        }
    });
```

|**1**|Using the method `getClobAsString` to retrieve the contents of the CLOB.|
|-----|------------------------------------------------------------------------|
|**2**|Using the method `getBlobAsBytes` to retrieve the contents of the BLOB. |

Kotlin

```
val l = jdbcTemplate.query("select id, a_clob, a_blob from lob_table") { rs, _ ->
    val clobText = lobHandler.getClobAsString(rs, "a_clob")  (1)
    val blobBytes = lobHandler.getBlobAsBytes(rs, "a_blob")  (2)
    mapOf("CLOB" to clobText, "BLOB" to blobBytes)
}
```

|**1**|Using the method `getClobAsString` to retrieve the contents of the CLOB.|
|-----|------------------------------------------------------------------------|
|**2**|Using the method `getBlobAsBytes` to retrieve the contents of the BLOB. |

#### [](#jdbc-in-clause)3.8.3. Passing in Lists of Values for IN Clause ####

The SQL standard allows for selecting rows based on an expression that includes a
variable list of values. A typical example would be `select * from T_ACTOR where id in
(1, 2, 3)`. This variable list is not directly supported for prepared statements by the
JDBC standard. You cannot declare a variable number of placeholders. You need a number
of variations with the desired number of placeholders prepared, or you need to generate
the SQL string dynamically once you know how many placeholders are required. The named
parameter support provided in the `NamedParameterJdbcTemplate` and `JdbcTemplate` takes
the latter approach. You can pass in the values as a `java.util.List` of primitive objects. This
list is used to insert the required placeholders and pass in the values during
statement execution.

|   |Be careful when passing in many values. The JDBC standard does not guarantee that you<br/>can use more than 100 values for an `in` expression list. Various databases exceed this<br/>number, but they usually have a hard limit for how many values are allowed. For example, Oracle’s<br/>limit is 1000.|
|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

In addition to the primitive values in the value list, you can create a `java.util.List`of object arrays. This list can support multiple expressions being defined for the `in`clause, such as `select * from T_ACTOR where (id, last_name) in ((1, 'Johnson'), (2,
'Harrop'))`. This, of course, requires that your database supports this syntax.

#### [](#jdbc-complex-types)3.8.4. Handling Complex Types for Stored Procedure Calls ####

When you call stored procedures, you can sometimes use complex types specific to the
database. To accommodate these types, Spring provides a `SqlReturnType` for handling
them when they are returned from the stored procedure call and `SqlTypeValue` when they
are passed in as a parameter to the stored procedure.

The `SqlReturnType` interface has a single method (named `getTypeValue`) that must be
implemented. This interface is used as part of the declaration of an `SqlOutParameter`.
The following example shows returning the value of an Oracle `STRUCT` object of the user
declared type `ITEM_TYPE`:

Java

```
public class TestItemStoredProcedure extends StoredProcedure {

    public TestItemStoredProcedure(DataSource dataSource) {
        // ...
        declareParameter(new SqlOutParameter("item", OracleTypes.STRUCT, "ITEM_TYPE",
            (CallableStatement cs, int colIndx, int sqlType, String typeName) -> {
                STRUCT struct = (STRUCT) cs.getObject(colIndx);
                Object[] attr = struct.getAttributes();
                TestItem item = new TestItem();
                item.setId(((Number) attr[0]).longValue());
                item.setDescription((String) attr[1]);
                item.setExpirationDate((java.util.Date) attr[2]);
                return item;
            }));
        // ...
    }
```

Kotlin

```
class TestItemStoredProcedure(dataSource: DataSource) : StoredProcedure() {

    init {
        // ...
        declareParameter(SqlOutParameter("item", OracleTypes.STRUCT, "ITEM_TYPE") { cs, colIndx, sqlType, typeName ->
            val struct = cs.getObject(colIndx) as STRUCT
            val attr = struct.getAttributes()
            TestItem((attr[0] as Long, attr[1] as String, attr[2] as Date)
        })
        // ...
    }
}
```

You can use `SqlTypeValue` to pass the value of a Java object (such as `TestItem`) to a
stored procedure. The `SqlTypeValue` interface has a single method (named`createTypeValue`) that you must implement. The active connection is passed in, and you
can use it to create database-specific objects, such as `StructDescriptor` instances
or `ArrayDescriptor` instances. The following example creates a `StructDescriptor` instance:

Java

```
final TestItem testItem = new TestItem(123L, "A test item",
        new SimpleDateFormat("yyyy-M-d").parse("2010-12-31"));

SqlTypeValue value = new AbstractSqlTypeValue() {
    protected Object createTypeValue(Connection conn, int sqlType, String typeName) throws SQLException {
        StructDescriptor itemDescriptor = new StructDescriptor(typeName, conn);
        Struct item = new STRUCT(itemDescriptor, conn,
        new Object[] {
            testItem.getId(),
            testItem.getDescription(),
            new java.sql.Date(testItem.getExpirationDate().getTime())
        });
        return item;
    }
};
```

Kotlin

```
val (id, description, expirationDate) = TestItem(123L, "A test item",
        SimpleDateFormat("yyyy-M-d").parse("2010-12-31"))

val value = object : AbstractSqlTypeValue() {
    override fun createTypeValue(conn: Connection, sqlType: Int, typeName: String?): Any {
        val itemDescriptor = StructDescriptor(typeName, conn)
        return STRUCT(itemDescriptor, conn,
                arrayOf(id, description, java.sql.Date(expirationDate.time)))
    }
}
```

You can now add this `SqlTypeValue` to the `Map` that contains the input parameters for the`execute` call of the stored procedure.

Another use for the `SqlTypeValue` is passing in an array of values to an Oracle stored
procedure. Oracle has its own internal `ARRAY` class that must be used in this case, and
you can use the `SqlTypeValue` to create an instance of the Oracle `ARRAY` and populate
it with values from the Java `ARRAY`, as the following example shows:

Java

```
final Long[] ids = new Long[] {1L, 2L};

SqlTypeValue value = new AbstractSqlTypeValue() {
    protected Object createTypeValue(Connection conn, int sqlType, String typeName) throws SQLException {
        ArrayDescriptor arrayDescriptor = new ArrayDescriptor(typeName, conn);
        ARRAY idArray = new ARRAY(arrayDescriptor, conn, ids);
        return idArray;
    }
};
```

Kotlin

```
class TestItemStoredProcedure(dataSource: DataSource) : StoredProcedure() {

    init {
        val ids = arrayOf(1L, 2L)
        val value = object : AbstractSqlTypeValue() {
            override fun createTypeValue(conn: Connection, sqlType: Int, typeName: String?): Any {
                val arrayDescriptor = ArrayDescriptor(typeName, conn)
                return ARRAY(arrayDescriptor, conn, ids)
            }
        }
    }
}
```

### [](#jdbc-embedded-database-support)3.9. Embedded Database Support ###

The `org.springframework.jdbc.datasource.embedded` package provides support for embedded
Java database engines. Support for [HSQL](http://www.hsqldb.org),[H2](https://www.h2database.com), and [Derby](https://db.apache.org/derby) is provided
natively. You can also use an extensible API to plug in new embedded database types and`DataSource` implementations.

#### [](#jdbc-why-embedded-database)3.9.1. Why Use an Embedded Database? ####

An embedded database can be useful during the development phase of a project because of its
lightweight nature. Benefits include ease of configuration, quick startup time,
testability, and the ability to rapidly evolve your SQL during development.

#### [](#jdbc-embedded-database-xml)3.9.2. Creating an Embedded Database by Using Spring XML ####

If you want to expose an embedded database instance as a bean in a Spring`ApplicationContext`, you can use the `embedded-database` tag in the `spring-jdbc` namespace:

```
<jdbc:embedded-database id="dataSource" generate-name="true">
    <jdbc:script location="classpath:schema.sql"/>
    <jdbc:script location="classpath:test-data.sql"/>
</jdbc:embedded-database>
```

The preceding configuration creates an embedded HSQL database that is populated with SQL from
the `schema.sql` and `test-data.sql` resources in the root of the classpath. In addition, as
a best practice, the embedded database is assigned a uniquely generated name. The
embedded database is made available to the Spring container as a bean of type`javax.sql.DataSource` that can then be injected into data access objects as needed.

#### [](#jdbc-embedded-database-java)3.9.3. Creating an Embedded Database Programmatically ####

The `EmbeddedDatabaseBuilder` class provides a fluent API for constructing an embedded
database programmatically. You can use this when you need to create an embedded database in a
stand-alone environment or in a stand-alone integration test, as in the following example:

Java

```
EmbeddedDatabase db = new EmbeddedDatabaseBuilder()
        .generateUniqueName(true)
        .setType(H2)
        .setScriptEncoding("UTF-8")
        .ignoreFailedDrops(true)
        .addScript("schema.sql")
        .addScripts("user_data.sql", "country_data.sql")
        .build();

// perform actions against the db (EmbeddedDatabase extends javax.sql.DataSource)

db.shutdown()
```

Kotlin

```
val db = EmbeddedDatabaseBuilder()
        .generateUniqueName(true)
        .setType(H2)
        .setScriptEncoding("UTF-8")
        .ignoreFailedDrops(true)
        .addScript("schema.sql")
        .addScripts("user_data.sql", "country_data.sql")
        .build()

// perform actions against the db (EmbeddedDatabase extends javax.sql.DataSource)

db.shutdown()
```

See the [javadoc for `EmbeddedDatabaseBuilder`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseBuilder.html)for further details on all supported options.

You can also use the `EmbeddedDatabaseBuilder` to create an embedded database by using Java
configuration, as the following example shows:

Java

```
@Configuration
public class DataSourceConfig {

    @Bean
    public DataSource dataSource() {
        return new EmbeddedDatabaseBuilder()
                .generateUniqueName(true)
                .setType(H2)
                .setScriptEncoding("UTF-8")
                .ignoreFailedDrops(true)
                .addScript("schema.sql")
                .addScripts("user_data.sql", "country_data.sql")
                .build();
    }
}
```

Kotlin

```
@Configuration
class DataSourceConfig {

    @Bean
    fun dataSource(): DataSource {
        return EmbeddedDatabaseBuilder()
                .generateUniqueName(true)
                .setType(H2)
                .setScriptEncoding("UTF-8")
                .ignoreFailedDrops(true)
                .addScript("schema.sql")
                .addScripts("user_data.sql", "country_data.sql")
                .build()
    }
}
```

#### [](#jdbc-embedded-database-types)3.9.4. Selecting the Embedded Database Type ####

This section covers how to select one of the three embedded databases that Spring
supports. It includes the following topics:

* [Using HSQL](#jdbc-embedded-database-using-HSQL)

* [Using H2](#jdbc-embedded-database-using-H2)

* [Using Derby](#jdbc-embedded-database-using-Derby)

##### [](#jdbc-embedded-database-using-HSQL)Using HSQL #####

Spring supports HSQL 1.8.0 and above. HSQL is the default embedded database if no type is
explicitly specified. To specify HSQL explicitly, set the `type` attribute of the`embedded-database` tag to `HSQL`. If you use the builder API, call the`setType(EmbeddedDatabaseType)` method with `EmbeddedDatabaseType.HSQL`.

##### [](#jdbc-embedded-database-using-H2)Using H2 #####

Spring supports the H2 database. To enable H2, set the `type` attribute of the`embedded-database` tag to `H2`. If you use the builder API, call the`setType(EmbeddedDatabaseType)` method with `EmbeddedDatabaseType.H2`.

##### [](#jdbc-embedded-database-using-Derby)Using Derby #####

Spring supports Apache Derby 10.5 and above. To enable Derby, set the `type`attribute of the `embedded-database` tag to `DERBY`. If you use the builder API,
call the `setType(EmbeddedDatabaseType)` method with `EmbeddedDatabaseType.DERBY`.

#### [](#jdbc-embedded-database-dao-testing)3.9.5. Testing Data Access Logic with an Embedded Database ####

Embedded databases provide a lightweight way to test data access code. The next example is a
data access integration test template that uses an embedded database. Using such a template
can be useful for one-offs when the embedded database does not need to be reused across test
classes. However, if you wish to create an embedded database that is shared within a test suite,
consider using the [Spring TestContext Framework](testing.html#testcontext-framework) and
configuring the embedded database as a bean in the Spring `ApplicationContext` as described
in [Creating an Embedded Database by Using Spring XML](#jdbc-embedded-database-xml) and [Creating an Embedded Database Programmatically](#jdbc-embedded-database-java). The following listing
shows the test template:

Java

```
public class DataAccessIntegrationTestTemplate {

    private EmbeddedDatabase db;

    @BeforeEach
    public void setUp() {
        // creates an HSQL in-memory database populated from default scripts
        // classpath:schema.sql and classpath:data.sql
        db = new EmbeddedDatabaseBuilder()
                .generateUniqueName(true)
                .addDefaultScripts()
                .build();
    }

    @Test
    public void testDataAccess() {
        JdbcTemplate template = new JdbcTemplate(db);
        template.query( /* ... */ );
    }

    @AfterEach
    public void tearDown() {
        db.shutdown();
    }

}
```

Kotlin

```
class DataAccessIntegrationTestTemplate {

    private lateinit var db: EmbeddedDatabase

    @BeforeEach
    fun setUp() {
        // creates an HSQL in-memory database populated from default scripts
        // classpath:schema.sql and classpath:data.sql
        db = EmbeddedDatabaseBuilder()
                .generateUniqueName(true)
                .addDefaultScripts()
                .build()
    }

    @Test
    fun testDataAccess() {
        val template = JdbcTemplate(db)
        template.query( /* ... */)
    }

    @AfterEach
    fun tearDown() {
        db.shutdown()
    }
}
```

#### [](#jdbc-embedded-database-unique-names)3.9.6. Generating Unique Names for Embedded Databases ####

Development teams often encounter errors with embedded databases if their test suite
inadvertently attempts to recreate additional instances of the same database. This can
happen quite easily if an XML configuration file or `@Configuration` class is responsible
for creating an embedded database and the corresponding configuration is then reused
across multiple testing scenarios within the same test suite (that is, within the same JVM
process) — for example, integration tests against embedded databases whose`ApplicationContext` configuration differs only with regard to which bean definition
profiles are active.

The root cause of such errors is the fact that Spring’s `EmbeddedDatabaseFactory` (used
internally by both the `<jdbc:embedded-database>` XML namespace element and the`EmbeddedDatabaseBuilder` for Java configuration) sets the name of the embedded database to`testdb` if not otherwise specified. For the case of `<jdbc:embedded-database>`, the
embedded database is typically assigned a name equal to the bean’s `id` (often,
something like `dataSource`). Thus, subsequent attempts to create an embedded database
do not result in a new database. Instead, the same JDBC connection URL is reused,
and attempts to create a new embedded database actually point to an existing
embedded database created from the same configuration.

To address this common issue, Spring Framework 4.2 provides support for generating
unique names for embedded databases. To enable the use of generated names, use one of
the following options.

* `EmbeddedDatabaseFactory.setGenerateUniqueDatabaseName()`

* `EmbeddedDatabaseBuilder.generateUniqueName()`

* `<jdbc:embedded-database generate-name="true" …​ >`

#### [](#jdbc-embedded-database-extension)3.9.7. Extending the Embedded Database Support ####

You can extend Spring JDBC embedded database support in two ways:

* Implement `EmbeddedDatabaseConfigurer` to support a new embedded database type.

* Implement `DataSourceFactory` to support a new `DataSource` implementation, such as a
  connection pool to manage embedded database connections.

We encourage you to contribute extensions to the Spring community at[GitHub Issues](https://github.com/spring-projects/spring-framework/issues).

### [](#jdbc-initializing-datasource)3.10. Initializing a `DataSource` ###

The `org.springframework.jdbc.datasource.init` package provides support for initializing
an existing `DataSource`. The embedded database support provides one option for creating
and initializing a `DataSource` for an application. However, you may sometimes need to initialize
an instance that runs on a server somewhere.

#### [](#jdbc-initializing-datasource-xml)3.10.1. Initializing a Database by Using Spring XML ####

If you want to initialize a database and you can provide a reference to a `DataSource`bean, you can use the `initialize-database` tag in the `spring-jdbc` namespace:

```
<jdbc:initialize-database data-source="dataSource">
    <jdbc:script location="classpath:com/foo/sql/db-schema.sql"/>
    <jdbc:script location="classpath:com/foo/sql/db-test-data.sql"/>
</jdbc:initialize-database>
```

The preceding example runs the two specified scripts against the database. The first
script creates a schema, and the second populates tables with a test data set. The script
locations can also be patterns with wildcards in the usual Ant style used for resources
in Spring (for example,`classpath*:/com/foo/**/sql/*-data.sql`). If you use a
pattern, the scripts are run in the lexical order of their URL or filename.

The default behavior of the database initializer is to unconditionally run the provided
scripts. This may not always be what you want — for instance, if you run
the scripts against a database that already has test data in it. The likelihood
of accidentally deleting data is reduced by following the common pattern (shown earlier)
of creating the tables first and then inserting the data. The first step fails if
the tables already exist.

However, to gain more control over the creation and deletion of existing data, the XML
namespace provides a few additional options. The first is a flag to switch the
initialization on and off. You can set this according to the environment (such as pulling a
boolean value from system properties or from an environment bean). The following example gets a value from a system property:

```
<jdbc:initialize-database data-source="dataSource"
    enabled="#{systemProperties.INITIALIZE_DATABASE}"> (1)
    <jdbc:script location="..."/>
</jdbc:initialize-database>
```

|**1**|Get the value for `enabled` from a system property called `INITIALIZE_DATABASE`.|
|-----|--------------------------------------------------------------------------------|

The second option to control what happens with existing data is to be more tolerant of
failures. To this end, you can control the ability of the initializer to ignore certain
errors in the SQL it runs from the scripts, as the following example shows:

```
<jdbc:initialize-database data-source="dataSource" ignore-failures="DROPS">
    <jdbc:script location="..."/>
</jdbc:initialize-database>
```

In the preceding example, we are saying that we expect that, sometimes, the scripts are run
against an empty database, and there are some `DROP` statements in the scripts that
would, therefore, fail. So failed SQL `DROP` statements will be ignored, but other failures
will cause an exception. This is useful if your SQL dialect doesn’t support `DROP …​ IF
EXISTS` (or similar) but you want to unconditionally remove all test data before
re-creating it. In that case the first script is usually a set of `DROP` statements,
followed by a set of `CREATE` statements.

The `ignore-failures` option can be set to `NONE` (the default), `DROPS` (ignore failed
drops), or `ALL` (ignore all failures).

Each statement should be separated by `;` or a new line if the `;` character is not
present at all in the script. You can control that globally or script by script, as the
following example shows:

```
<jdbc:initialize-database data-source="dataSource" separator="@@"> (1)
    <jdbc:script location="classpath:com/myapp/sql/db-schema.sql" separator=";"/> (2)
    <jdbc:script location="classpath:com/myapp/sql/db-test-data-1.sql"/>
    <jdbc:script location="classpath:com/myapp/sql/db-test-data-2.sql"/>
</jdbc:initialize-database>
```

|**1**|     Set the separator scripts to `@@`.      |
|-----|---------------------------------------------|
|**2**|Set the separator for `db-schema.sql` to `;`.|

In this example, the two `test-data` scripts use `@@` as statement separator and only
the `db-schema.sql` uses `;`. This configuration specifies that the default separator
is `@@` and overrides that default for the `db-schema` script.

If you need more control than you get from the XML namespace, you can use the`DataSourceInitializer` directly and define it as a component in your application.

##### [](#jdbc-client-component-initialization)Initialization of Other Components that Depend on the Database #####

A large class of applications (those that do not use the database until after the Spring context has
started) can use the database initializer with no further
complications. If your application is not one of those, you might need to read the rest
of this section.

The database initializer depends on a `DataSource` instance and runs the scripts
provided in its initialization callback (analogous to an `init-method` in an XML bean
definition, a `@PostConstruct` method in a component, or the `afterPropertiesSet()`method in a component that implements `InitializingBean`). If other beans depend on the
same data source and use the data source in an initialization callback, there
might be a problem because the data has not yet been initialized. A common example of
this is a cache that initializes eagerly and loads data from the database on application
startup.

To get around this issue, you have two options: change your cache initialization strategy
to a later phase or ensure that the database initializer is initialized first.

Changing your cache initialization strategy might be easy if the application is in your control and not otherwise.
Some suggestions for how to implement this include:

* Make the cache initialize lazily on first usage, which improves application startup
  time.

* Have your cache or a separate component that initializes the cache implement`Lifecycle` or `SmartLifecycle`. When the application context starts, you can
  automatically start a `SmartLifecycle` by setting its `autoStartup` flag, and you can
  manually start a `Lifecycle` by calling `ConfigurableApplicationContext.start()`on the enclosing context.

* Use a Spring `ApplicationEvent` or similar custom observer mechanism to trigger the
  cache initialization. `ContextRefreshedEvent` is always published by the context when
  it is ready for use (after all beans have been initialized), so that is often a useful
  hook (this is how the `SmartLifecycle` works by default).

Ensuring that the database initializer is initialized first can also be easy. Some suggestions on how to implement this include:

* Rely on the default behavior of the Spring `BeanFactory`, which is that beans are
  initialized in registration order. You can easily arrange that by adopting the common
  practice of a set of `<import/>` elements in XML configuration that order your
  application modules and ensuring that the database and database initialization are
  listed first.

* Separate the `DataSource` and the business components that use it and control their
  startup order by putting them in separate `ApplicationContext` instances (for example, the
  parent context contains the `DataSource`, and the child context contains the business
  components). This structure is common in Spring web applications but can be more
  generally applied.

[](#r2dbc)4. Data Access with R2DBC
----------

[R2DBC](https://r2dbc.io) ("Reactive Relational Database Connectivity") is a community-driven
specification effort to standardize access to SQL databases using reactive patterns.

### [](#r2dbc-packages)4.1. Package Hierarchy ###

The Spring Framework’s R2DBC abstraction framework consists of two different packages:

* `core`: The `org.springframework.r2dbc.core` package contains the `DatabaseClient`class plus a variety of related classes. See [Using the R2DBC Core Classes to Control Basic R2DBC Processing and Error Handling](#r2dbc-core).

* `connection`: The `org.springframework.r2dbc.connection` package contains a utility class
  for easy `ConnectionFactory` access and various simple `ConnectionFactory` implementations
  that you can use for testing and running unmodified R2DBC. See [Controlling Database Connections](#r2dbc-connections).

### [](#r2dbc-core)4.2. Using the R2DBC Core Classes to Control Basic R2DBC Processing and Error Handling ###

This section covers how to use the R2DBC core classes to control basic R2DBC processing,
including error handling. It includes the following topics:

* [Using `DatabaseClient`](#r2dbc-DatabaseClient)

* [Executing Statements](#r2dbc-DatabaseClient-examples-statement)

* [Querying (`SELECT`)](#r2dbc-DatabaseClient-examples-query)

* [Updating (`INSERT`, `UPDATE`, and `DELETE`) with `DatabaseClient`](#r2dbc-DatabaseClient-examples-update)

* [Statement Filters](#r2dbc-DatabaseClient-filter)

* [Retrieving Auto-generated Keys](#r2dbc-auto-generated-keys)

#### [](#r2dbc-DatabaseClient)4.2.1. Using `DatabaseClient` ####

`DatabaseClient` is the central class in the R2DBC core package. It handles the
creation and release of resources, which helps to avoid common errors, such as
forgetting to close the connection. It performs the basic tasks of the core R2DBC
workflow (such as statement creation and execution), leaving application code to provide
SQL and extract results. The `DatabaseClient` class:

* Runs SQL queries

* Update statements and stored procedure calls

* Performs iteration over `Result` instances

* Catches R2DBC exceptions and translates them to the generic, more informative, exception
  hierarchy defined in the `org.springframework.dao` package. (See [Consistent Exception Hierarchy](#dao-exceptions).)

The client has a functional, fluent API using reactive types for declarative composition.

When you use the `DatabaseClient` for your code, you need only to implement`java.util.function` interfaces, giving them a clearly defined contract.
Given a `Connection` provided by the `DatabaseClient` class, a `Function`callback creates a `Publisher`. The same is true for mapping functions that
extract a `Row` result.

You can use `DatabaseClient` within a DAO implementation through direct instantiation
with a `ConnectionFactory` reference, or you can configure it in a Spring IoC container
and give it to DAOs as a bean reference.

The simplest way to create a `DatabaseClient` object is through a static factory method, as follows:

Java

```
DatabaseClient client = DatabaseClient.create(connectionFactory);
```

Kotlin

```
val client = DatabaseClient.create(connectionFactory)
```

|   |The `ConnectionFactory` should always be configured as a bean in the Spring IoC<br/>container.|
|---|----------------------------------------------------------------------------------------------|

The preceding method creates a `DatabaseClient` with default settings.

You can also obtain a `Builder` instance from `DatabaseClient.builder()`.
You can customize the client by calling the following methods:

* `….bindMarkers(…)`: Supply a specific `BindMarkersFactory` to configure named
  parameter to database bind marker translation.

* `….executeFunction(…)`: Set the `ExecuteFunction` how `Statement` objects get
  run.

* `….namedParameters(false)`: Disable named parameter expansion. Enabled by default.

|   |Dialects are resolved by [`BindMarkersFactoryResolver`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/r2dbc/core/binding/BindMarkersFactoryResolver.html)from a `ConnectionFactory`, typically by inspecting `ConnectionFactoryMetadata`.  <br/>You can let Spring auto-discover your `BindMarkersFactory` by registering a<br/>class that implements `org.springframework.r2dbc.core.binding.BindMarkersFactoryResolver$BindMarkerFactoryProvider`through `META-INF/spring.factories`.`BindMarkersFactoryResolver` discovers bind marker provider implementations from<br/>the class path using Spring’s `SpringFactoriesLoader`.|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

Currently supported databases are:

* H2

* MariaDB

* Microsoft SQL Server

* MySQL

* Postgres

All SQL issued by this class is logged at the `DEBUG` level under the category
corresponding to the fully qualified class name of the client instance (typically`DefaultDatabaseClient`). Additionally, each execution registers a checkpoint in
the reactive sequence to aid debugging.

The following sections provide some examples of `DatabaseClient` usage. These examples
are not an exhaustive list of all of the functionality exposed by the `DatabaseClient`.
See the attendant [javadoc](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/r2dbc/core/DatabaseClient.html) for that.

##### [](#r2dbc-DatabaseClient-examples-statement)Executing Statements #####

`DatabaseClient` provides the basic functionality of running a statement.
The following example shows what you need to include for minimal but fully functional
code that creates a new table:

Java

```
Mono<Void> completion = client.sql("CREATE TABLE person (id VARCHAR(255) PRIMARY KEY, name VARCHAR(255), age INTEGER);")
        .then();
```

Kotlin

```
client.sql("CREATE TABLE person (id VARCHAR(255) PRIMARY KEY, name VARCHAR(255), age INTEGER);")
        .await()
```

`DatabaseClient` is designed for convenient, fluent usage.
It exposes intermediate, continuation, and terminal methods at each stage of the
execution specification. The preceding example above uses `then()` to return a completion`Publisher` that completes as soon as the query (or queries, if the SQL query contains
multiple statements) completes.

|   |`execute(…)` accepts either the SQL query string or a query `Supplier<String>`to defer the actual query creation until execution.|
|---|---------------------------------------------------------------------------------------------------------------------------------|

##### [](#r2dbc-DatabaseClient-examples-query)Querying (`SELECT`) #####

SQL queries can return values through `Row` objects or the number of affected rows.`DatabaseClient` can return the number of updated rows or the rows themselves,
depending on the issued query.

The following query gets the `id` and `name` columns from a table:

Java

```
Mono<Map<String, Object>> first = client.sql("SELECT id, name FROM person")
        .fetch().first();
```

Kotlin

```
val first = client.sql("SELECT id, name FROM person")
        .fetch().awaitSingle()
```

The following query uses a bind variable:

Java

```
Mono<Map<String, Object>> first = client.sql("SELECT id, name FROM person WHERE first_name = :fn")
        .bind("fn", "Joe")
        .fetch().first();
```

Kotlin

```
val first = client.sql("SELECT id, name FROM person WHERE WHERE first_name = :fn")
        .bind("fn", "Joe")
        .fetch().awaitSingle()
```

You might have noticed the use of `fetch()` in the example above. `fetch()` is a
continuation operator that lets you specify how much data you want to consume.

Calling `first()` returns the first row from the result and discards remaining rows.
You can consume data with the following operators:

* `first()` return the first row of the entire result. Its Kotlin Coroutine variant
  is named `awaitSingle()` for non-nullable return values and `awaitSingleOrNull()`if the value is optional.

* `one()` returns exactly one result and fails if the result contains more rows.
  Using Kotlin Coroutines, `awaitOne()` for exactly one value or `awaitOneOrNull()`if the value may be `null`.

* `all()` returns all rows of the result. When using Kotlin Coroutines, use `flow()`.

* `rowsUpdated()` returns the number of affected rows (`INSERT`/`UPDATE`/`DELETE`count). Its Kotlin Coroutine variant is named `awaitRowsUpdated()`.

Without specifying further mapping details, queries return tabular results
as `Map` whose keys are case-insensitive column names that map to their column value.

You can take control over result mapping by supplying a `Function<Row, T>` that gets
called for each `Row` so it can can return arbitrary values (singular values,
collections and maps, and objects).

The following example extracts the `name` column and emits its value:

Java

```
Flux<String> names = client.sql("SELECT name FROM person")
        .map(row -> row.get("name", String.class))
        .all();
```

Kotlin

```
val names = client.sql("SELECT name FROM person")
        .map{ row: Row -> row.get("name", String.class) }
        .flow()
```

What about `null`?

Relational database results can contain `null` values.
The Reactive Streams specification forbids the emission of `null` values.
That requirement mandates proper `null` handling in the extractor function.
While you can obtain `null` values from a `Row`, you must not emit a `null`value. You must wrap any `null` values in an object (for example, `Optional`for singular values) to make sure a `null` value is never returned directly
by your extractor function.

##### [](#r2dbc-DatabaseClient-examples-update)Updating (`INSERT`, `UPDATE`, and `DELETE`) with `DatabaseClient` #####

The only difference of modifying statements is that these statements typically
do not return tabular data so you use `rowsUpdated()` to consume results.

The following example shows an `UPDATE` statement that returns the number
of updated rows:

Java

```
Mono<Integer> affectedRows = client.sql("UPDATE person SET first_name = :fn")
        .bind("fn", "Joe")
        .fetch().rowsUpdated();
```

Kotlin

```
val affectedRows = client.sql("UPDATE person SET first_name = :fn")
        .bind("fn", "Joe")
        .fetch().awaitRowsUpdated()
```

##### [](#r2dbc-DatabaseClient-named-parameters)Binding Values to Queries #####

A typical application requires parameterized SQL statements to select or
update rows according to some input. These are typically `SELECT` statements
constrained by a `WHERE` clause or `INSERT` and `UPDATE` statements that accept
input parameters. Parameterized statements bear the risk of SQL injection if
parameters are not escaped properly. `DatabaseClient` leverages R2DBC’s`bind` API to eliminate the risk of SQL injection for query parameters.
You can provide a parameterized SQL statement with the `execute(…)` operator
and bind parameters to the actual `Statement`. Your R2DBC driver then runs
the statement by using prepared statements and parameter substitution.

Parameter binding supports two binding strategies:

* By Index, using zero-based parameter indexes.

* By Name, using the placeholder name.

The following example shows parameter binding for a query:

```
db.sql("INSERT INTO person (id, name, age) VALUES(:id, :name, :age)")
    .bind("id", "joe")
    .bind("name", "Joe")
    .bind("age", 34);
```

R2DBC Native Bind Markers

R2DBC uses database-native bind markers that depend on the actual database vendor.
As an example, Postgres uses indexed markers, such as `$1`, `$2`, `$n`.
Another example is SQL Server, which uses named bind markers prefixed with `@`.

This is different from JDBC, which requires `?` as bind markers.
In JDBC, the actual drivers translate `?` bind markers to database-native
markers as part of their statement execution.

Spring Framework’s R2DBC support lets you use native bind markers or named bind
markers with the `:name` syntax.

Named parameter support leverages a `BindMarkersFactory` instance to expand named
parameters to native bind markers at the time of query execution, which gives you
a certain degree of query portability across various database vendors.

The query-preprocessor unrolls named `Collection` parameters into a series of bind
markers to remove the need of dynamic query creation based on the number of arguments.
Nested object arrays are expanded to allow usage of (for example) select lists.

Consider the following query:

```
SELECT id, name, state FROM table WHERE (name, age) IN (('John', 35), ('Ann', 50))
```

The preceding query can be parametrized and run as follows:

Java

```
List<Object[]> tuples = new ArrayList<>();
tuples.add(new Object[] {"John", 35});
tuples.add(new Object[] {"Ann",  50});

client.sql("SELECT id, name, state FROM table WHERE (name, age) IN (:tuples)")
    .bind("tuples", tuples);
```

Kotlin

```
val tuples: MutableList<Array<Any>> = ArrayList()
tuples.add(arrayOf("John", 35))
tuples.add(arrayOf("Ann", 50))

client.sql("SELECT id, name, state FROM table WHERE (name, age) IN (:tuples)")
    .bind("tuples", tuples)
```

|   |Usage of select lists is vendor-dependent.|
|---|------------------------------------------|

The following example shows a simpler variant using `IN` predicates:

Java

```
client.sql("SELECT id, name, state FROM table WHERE age IN (:ages)")
    .bind("ages", Arrays.asList(35, 50));
```

Kotlin

```
val tuples: MutableList<Array<Any>> = ArrayList()
tuples.add(arrayOf("John", 35))
tuples.add(arrayOf("Ann", 50))

client.sql("SELECT id, name, state FROM table WHERE age IN (:ages)")
    .bind("tuples", arrayOf(35, 50))
```

|   |R2DBC itself does not support Collection-like values. Nevertheless,<br/>expanding a given `List` in the example above works for named parameters<br/>in Spring’s R2DBC support, e.g. for use in `IN` clauses as shown above.<br/>However, inserting or updating array-typed columns (e.g. in Postgres)<br/>requires an array type that is supported by the underlying R2DBC driver:<br/>typically a Java array, e.g. `String[]` to update a `text[]` column.<br/>Do not pass `Collection<String>` or the like as an array parameter.|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

##### [](#r2dbc-DatabaseClient-filter)Statement Filters #####

Sometimes it you need to fine-tune options on the actual `Statement`before it gets run. Register a `Statement` filter
(`StatementFilterFunction`) through `DatabaseClient` to intercept and
modify statements in their execution, as the following example shows:

Java

```
client.sql("INSERT INTO table (name, state) VALUES(:name, :state)")
    .filter((s, next) -> next.execute(s.returnGeneratedValues("id")))
    .bind("name", …)
    .bind("state", …);
```

Kotlin

```
client.sql("INSERT INTO table (name, state) VALUES(:name, :state)")
            .filter { s: Statement, next: ExecuteFunction -> next.execute(s.returnGeneratedValues("id")) }
            .bind("name", …)
            .bind("state", …)
```

`DatabaseClient` exposes also simplified `filter(…)` overload accepting `Function<Statement, Statement>`:

Java

```
client.sql("INSERT INTO table (name, state) VALUES(:name, :state)")
    .filter(statement -> s.returnGeneratedValues("id"));

client.sql("SELECT id, name, state FROM table")
    .filter(statement -> s.fetchSize(25));
```

Kotlin

```
client.sql("INSERT INTO table (name, state) VALUES(:name, :state)")
    .filter { statement -> s.returnGeneratedValues("id") }

client.sql("SELECT id, name, state FROM table")
    .filter { statement -> s.fetchSize(25) }
```

`StatementFilterFunction` implementations allow filtering of the`Statement` and filtering of `Result` objects.

##### [](#r2dbc-DatabaseClient-idioms)`DatabaseClient` Best Practices #####

Instances of the `DatabaseClient` class are thread-safe, once configured. This is
important because it means that you can configure a single instance of a `DatabaseClient`and then safely inject this shared reference into multiple DAOs (or repositories).
The `DatabaseClient` is stateful, in that it maintains a reference to a `ConnectionFactory`,
but this state is not conversational state.

A common practice when using the `DatabaseClient` class is to configure a `ConnectionFactory`in your Spring configuration file and then dependency-inject
that shared `ConnectionFactory` bean into your DAO classes. The `DatabaseClient` is created in
the setter for the `ConnectionFactory`. This leads to DAOs that resemble the following:

Java

```
public class R2dbcCorporateEventDao implements CorporateEventDao {

    private DatabaseClient databaseClient;

    public void setConnectionFactory(ConnectionFactory connectionFactory) {
        this.databaseClient = DatabaseClient.create(connectionFactory);
    }

    // R2DBC-backed implementations of the methods on the CorporateEventDao follow...
}
```

Kotlin

```
class R2dbcCorporateEventDao(connectionFactory: ConnectionFactory) : CorporateEventDao {

    private val databaseClient = DatabaseClient.create(connectionFactory)

    // R2DBC-backed implementations of the methods on the CorporateEventDao follow...
}
```

An alternative to explicit configuration is to use component-scanning and annotation
support for dependency injection. In this case, you can annotate the class with `@Component`(which makes it a candidate for component-scanning) and annotate the `ConnectionFactory` setter
method with `@Autowired`. The following example shows how to do so:

Java

```
@Component (1)
public class R2dbcCorporateEventDao implements CorporateEventDao {

    private DatabaseClient databaseClient;

    @Autowired (2)
    public void setConnectionFactory(ConnectionFactory connectionFactory) {
        this.databaseClient = DatabaseClient.create(connectionFactory); (3)
    }

    // R2DBC-backed implementations of the methods on the CorporateEventDao follow...
}
```

|**1**|              Annotate the class with `@Component`.              |
|-----|-----------------------------------------------------------------|
|**2**|Annotate the `ConnectionFactory` setter method with `@Autowired`.|
|**3**|   Create a new `DatabaseClient` with the `ConnectionFactory`.   |

Kotlin

```
@Component (1)
class R2dbcCorporateEventDao(connectionFactory: ConnectionFactory) : CorporateEventDao { (2)

    private val databaseClient = DatabaseClient(connectionFactory) (3)

    // R2DBC-backed implementations of the methods on the CorporateEventDao follow...
}
```

|**1**|           Annotate the class with `@Component`.           |
|-----|-----------------------------------------------------------|
|**2**|     Constructor injection of the `ConnectionFactory`.     |
|**3**|Create a new `DatabaseClient` with the `ConnectionFactory`.|

Regardless of which of the above template initialization styles you choose to use (or
not), it is seldom necessary to create a new instance of a `DatabaseClient` class each
time you want to run SQL. Once configured, a `DatabaseClient` instance is thread-safe.
If your application accesses multiple
databases, you may want multiple `DatabaseClient` instances, which requires multiple`ConnectionFactory` and, subsequently, multiple differently configured `DatabaseClient`instances.

### [](#r2dbc-auto-generated-keys)4.3. Retrieving Auto-generated Keys ###

`INSERT` statements may generate keys when inserting rows into a table
that defines an auto-increment or identity column. To get full control over
the column name to generate, simply register a `StatementFilterFunction` that
requests the generated key for the desired column.

Java

```
Mono<Integer> generatedId = client.sql("INSERT INTO table (name, state) VALUES(:name, :state)")
    .filter(statement -> s.returnGeneratedValues("id"))
        .map(row -> row.get("id", Integer.class))
        .first();

// generatedId emits the generated key once the INSERT statement has finished
```

Kotlin

```
val generatedId = client.sql("INSERT INTO table (name, state) VALUES(:name, :state)")
    .filter { statement -> s.returnGeneratedValues("id") }
        .map { row -> row.get("id", Integer.class) }
        .awaitOne()

// generatedId emits the generated key once the INSERT statement has finished
```

### [](#r2dbc-connections)4.4. Controlling Database Connections ###

This section covers:

* [Using `ConnectionFactory`](#r2dbc-ConnectionFactory)

* [Using `ConnectionFactoryUtils`](#r2dbc-ConnectionFactoryUtils)

* [Using `SingleConnectionFactory`](#r2dbc-SingleConnectionFactory)

* [Using `TransactionAwareConnectionFactoryProxy`](#r2dbc-TransactionAwareConnectionFactoryProxy)

* [Using `R2dbcTransactionManager`](#r2dbc-R2dbcTransactionManager)

#### [](#r2dbc-ConnectionFactory)4.4.1. Using `ConnectionFactory` ####

Spring obtains an R2DBC connection to the database through a `ConnectionFactory`.
A `ConnectionFactory` is part of the R2DBC specification and is a common entry-point
for drivers. It lets a container or a framework hide connection pooling
and transaction management issues from the application code. As a developer,
you need not know details about how to connect to the database. That is the
responsibility of the administrator who sets up the `ConnectionFactory`. You
most likely fill both roles as you develop and test code, but you do not
necessarily have to know how the production data source is configured.

When you use Spring’s R2DBC layer, you can can configure your own with a
connection pool implementation provided by a third party. A popular
implementation is R2DBC Pool (`r2dbc-pool`). Implementations in the Spring
distribution are meant only for testing purposes and do not provide pooling.

To configure a `ConnectionFactory`:

1. Obtain a connection with `ConnectionFactory` as you typically obtain an R2DBC `ConnectionFactory`.

2. Provide an R2DBC URL
   (See the documentation for your driver for the correct value).

The following example shows how to configure a `ConnectionFactory`:

Java

```
ConnectionFactory factory = ConnectionFactories.get("r2dbc:h2:mem:///test?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
```

Kotlin

```
val factory = ConnectionFactories.get("r2dbc:h2:mem:///test?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
```

#### [](#r2dbc-ConnectionFactoryUtils)4.4.2. Using `ConnectionFactoryUtils` ####

The `ConnectionFactoryUtils` class is a convenient and powerful helper class
that provides `static` methods to obtain connections from `ConnectionFactory`and close connections (if necessary).

It supports subscriber `Context`-bound connections with, for example`R2dbcTransactionManager`.

#### [](#r2dbc-SingleConnectionFactory)4.4.3. Using `SingleConnectionFactory` ####

The `SingleConnectionFactory` class is an implementation of `DelegatingConnectionFactory`interface that wraps a single `Connection` that is not closed after each use.

If any client code calls `close` on the assumption of a pooled connection (as when using
persistence tools), you should set the `suppressClose` property to `true`. This setting
returns a close-suppressing proxy that wraps the physical connection. Note that you can
no longer cast this to a native `Connection` or a similar object.

`SingleConnectionFactory` is primarily a test class and may be used for specific requirements
such as pipelining if your R2DBC driver permits for such use.
In contrast to a pooled `ConnectionFactory`, it reuses the same connection all the time, avoiding
excessive creation of physical connections.

#### [](#r2dbc-TransactionAwareConnectionFactoryProxy)4.4.4. Using `TransactionAwareConnectionFactoryProxy` ####

`TransactionAwareConnectionFactoryProxy` is a proxy for a target `ConnectionFactory`.
The proxy wraps that target `ConnectionFactory` to add awareness of Spring-managed transactions.

|   |Using this class is required if you use a R2DBC client that is not integrated otherwise<br/>with Spring’s R2DBC support. In this case, you can still use this client and, at<br/>the same time, have this client participating in Spring managed transactions. It is generally<br/>preferable to integrate a R2DBC client with proper access to `ConnectionFactoryUtils`for resource management.|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

See the [`TransactionAwareConnectionFactoryProxy`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/r2dbc/connection/TransactionAwareConnectionFactoryProxy.html)javadoc for more details.

#### [](#r2dbc-R2dbcTransactionManager)4.4.5. Using `R2dbcTransactionManager` ####

The `R2dbcTransactionManager` class is a `ReactiveTransactionManager` implementation for
single R2DBC datasources. It binds an R2DBC connection from the specified connection factory
to the subscriber `Context`, potentially allowing for one subscriber connection for each
connection factory.

Application code is required to retrieve the R2DBC connection through`ConnectionFactoryUtils.getConnection(ConnectionFactory)`, instead of R2DBC’s standard`ConnectionFactory.create()`.

All framework classes (such as `DatabaseClient`) use this strategy implicitly.
If not used with this transaction manager, the lookup strategy behaves exactly like the common one.
Thus, it can be used in any case.

The `R2dbcTransactionManager` class supports custom isolation levels that get applied to the connection.

[](#orm)5. Object Relational Mapping (ORM) Data Access
----------

This section covers data access when you use Object Relational Mapping (ORM).

### [](#orm-introduction)5.1. Introduction to ORM with Spring ###

The Spring Framework supports integration with the Java Persistence API (JPA) and
supports native Hibernate for resource management, data access object (DAO) implementations,
and transaction strategies. For example, for Hibernate, there is first-class support with
several convenient IoC features that address many typical Hibernate integration issues.
You can configure all of the supported features for OR (object relational) mapping
tools through Dependency Injection. They can participate in Spring’s resource and
transaction management, and they comply with Spring’s generic transaction and DAO
exception hierarchies. The recommended integration style is to code DAOs against plain
Hibernate or JPA APIs.

Spring adds significant enhancements to the ORM layer of your choice when you create
data access applications. You can leverage as much of the integration support as you
wish, and you should compare this integration effort with the cost and risk of building
a similar infrastructure in-house. You can use much of the ORM support as you would a
library, regardless of technology, because everything is designed as a set of reusable
JavaBeans. ORM in a Spring IoC container facilitates configuration and deployment. Thus,
most examples in this section show configuration inside a Spring container.

The benefits of using the Spring Framework to create your ORM DAOs include:

* **Easier testing.** Spring’s IoC approach makes it easy to swap the implementations
  and configuration locations of Hibernate `SessionFactory` instances, JDBC `DataSource`instances, transaction managers, and mapped object implementations (if needed). This
  in turn makes it much easier to test each piece of persistence-related code in
  isolation.

* **Common data access exceptions.** Spring can wrap exceptions from your ORM tool,
  converting them from proprietary (potentially checked) exceptions to a common runtime`DataAccessException` hierarchy. This feature lets you handle most persistence
  exceptions, which are non-recoverable, only in the appropriate layers, without
  annoying boilerplate catches, throws, and exception declarations. You can still trap
  and handle exceptions as necessary. Remember that JDBC exceptions (including
  DB-specific dialects) are also converted to the same hierarchy, meaning that you can
  perform some operations with JDBC within a consistent programming model.

* **General resource management.** Spring application contexts can handle the location
  and configuration of Hibernate `SessionFactory` instances, JPA `EntityManagerFactory`instances, JDBC `DataSource` instances, and other related resources. This makes these
  values easy to manage and change. Spring offers efficient, easy, and safe handling of
  persistence resources. For example, related code that uses Hibernate generally needs to
  use the same Hibernate `Session` to ensure efficiency and proper transaction handling.
  Spring makes it easy to create and bind a `Session` to the current thread transparently,
  by exposing a current `Session` through the Hibernate `SessionFactory`. Thus, Spring
  solves many chronic problems of typical Hibernate usage, for any local or JTA
  transaction environment.

* **Integrated transaction management.** You can wrap your ORM code with a declarative,
  aspect-oriented programming (AOP) style method interceptor either through the`@Transactional` annotation or by explicitly configuring the transaction AOP advice in
  an XML configuration file. In both cases, transaction semantics and exception handling
  (rollback and so on) are handled for you. As discussed in [Resource and Transaction Management](#orm-resource-mngmnt),
  you can also swap various transaction managers, without affecting your ORM-related code.
  For example, you can swap between local transactions and JTA, with the same full services
  (such as declarative transactions) available in both scenarios. Additionally,
  JDBC-related code can fully integrate transactionally with the code you use to do ORM.
  This is useful for data access that is not suitable for ORM (such as batch processing and
  BLOB streaming) but that still needs to share common transactions with ORM operations.

|   |For more comprehensive ORM support, including support for alternative database<br/>technologies such as MongoDB, you might want to check out the[Spring Data](https://projects.spring.io/spring-data/) suite of projects. If you are<br/>a JPA user, the [Getting Started Accessing<br/>Data with JPA](https://spring.io/guides/gs/accessing-data-jpa/) guide from [https://spring.io](https://spring.io) provides a great introduction.|
|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

### [](#orm-general)5.2. General ORM Integration Considerations ###

This section highlights considerations that apply to all ORM technologies.
The [Hibernate](#orm-hibernate) section provides more details and also show these features and
configurations in a concrete context.

The major goal of Spring’s ORM integration is clear application layering (with any data
access and transaction technology) and for loose coupling of application objects — no
more business service dependencies on the data access or transaction strategy, no more
hard-coded resource lookups, no more hard-to-replace singletons, no more custom service
registries. The goal is to have one simple and consistent approach to wiring up application objects, keeping
them as reusable and free from container dependencies as possible. All the individual
data access features are usable on their own but integrate nicely with Spring’s
application context concept, providing XML-based configuration and cross-referencing of
plain JavaBean instances that need not be Spring-aware. In a typical Spring application,
many important objects are JavaBeans: data access templates, data access objects,
transaction managers, business services that use the data access objects and transaction
managers, web view resolvers, web controllers that use the business services, and so on.

#### [](#orm-resource-mngmnt)5.2.1. Resource and Transaction Management ####

Typical business applications are cluttered with repetitive resource management code.
Many projects try to invent their own solutions, sometimes sacrificing proper handling
of failures for programming convenience. Spring advocates simple solutions for proper
resource handling, namely IoC through templating in the case of JDBC and applying AOP
interceptors for the ORM technologies.

The infrastructure provides proper resource handling and appropriate conversion of
specific API exceptions to an unchecked infrastructure exception hierarchy. Spring
introduces a DAO exception hierarchy, applicable to any data access strategy. For direct
JDBC, the `JdbcTemplate` class mentioned in a [previous section](#jdbc-JdbcTemplate)provides connection handling and proper conversion of `SQLException` to the`DataAccessException` hierarchy, including translation of database-specific SQL error
codes to meaningful exception classes. For ORM technologies, see the[next section](#orm-exception-translation) for how to get the same exception
translation benefits.

When it comes to transaction management, the `JdbcTemplate` class hooks in to the Spring
transaction support and supports both JTA and JDBC transactions, through respective
Spring transaction managers. For the supported ORM technologies, Spring offers Hibernate
and JPA support through the Hibernate and JPA transaction managers as well as JTA support.
For details on transaction support, see the [Transaction Management](#transaction) chapter.

#### [](#orm-exception-translation)5.2.2. Exception Translation ####

When you use Hibernate or JPA in a DAO, you must decide how to handle the persistence
technology’s native exception classes. The DAO throws a subclass of a `HibernateException`or `PersistenceException`, depending on the technology. These exceptions are all runtime
exceptions and do not have to be declared or caught. You may also have to deal with`IllegalArgumentException` and `IllegalStateException`. This means that callers can only
treat exceptions as being generally fatal, unless they want to depend on the persistence
technology’s own exception structure. Catching specific causes (such as an optimistic
locking failure) is not possible without tying the caller to the implementation strategy.
This trade-off might be acceptable to applications that are strongly ORM-based or
do not need any special exception treatment (or both). However, Spring lets exception
translation be applied transparently through the `@Repository` annotation. The following
examples (one for Java configuration and one for XML configuration) show how to do so:

Java

```
@Repository
public class ProductDaoImpl implements ProductDao {

    // class body here...

}
```

Kotlin

```
@Repository
class ProductDaoImpl : ProductDao {

    // class body here...

}
```

```
<beans>

    <!-- Exception translation bean post processor -->
    <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>

    <bean id="myProductDao" class="product.ProductDaoImpl"/>

</beans>
```

The postprocessor automatically looks for all exception translators (implementations of
the `PersistenceExceptionTranslator` interface) and advises all beans marked with the`@Repository` annotation so that the discovered translators can intercept and apply the
appropriate translation on the thrown exceptions.

In summary, you can implement DAOs based on the plain persistence technology’s API and
annotations while still benefiting from Spring-managed transactions, dependency
injection, and transparent exception conversion (if desired) to Spring’s custom
exception hierarchies.

### [](#orm-hibernate)5.3. Hibernate ###

We start with a coverage of [Hibernate 5](https://hibernate.org/) in a Spring environment,
using it to demonstrate the approach that Spring takes towards integrating OR mappers.
This section covers many issues in detail and shows different variations of DAO
implementations and transaction demarcation. Most of these patterns can be directly
translated to all other supported ORM tools. The later sections in this chapter then
cover the other ORM technologies and show brief examples.

|   |As of Spring Framework 5.3, Spring requires Hibernate ORM 5.2+ for Spring’s`HibernateJpaVendorAdapter` as well as for a native Hibernate `SessionFactory` setup.<br/>It is strongly recommended to go with Hibernate ORM 5.4 for a newly started application.<br/>For use with `HibernateJpaVendorAdapter`, Hibernate Search needs to be upgraded to 5.11.6.|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

#### [](#orm-session-factory-setup)5.3.1. `SessionFactory` Setup in a Spring Container ####

To avoid tying application objects to hard-coded resource lookups, you can define
resources (such as a JDBC `DataSource` or a Hibernate `SessionFactory`) as beans in the
Spring container. Application objects that need to access resources receive references
to such predefined instances through bean references, as illustrated in the DAO
definition in the [next section](#orm-hibernate-straight).

The following excerpt from an XML application context definition shows how to set up a
JDBC `DataSource` and a Hibernate `SessionFactory` on top of it:

```
<beans>

    <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
        <property name="url" value="jdbc:hsqldb:hsql://localhost:9001"/>
        <property name="username" value="sa"/>
        <property name="password" value=""/>
    </bean>

    <bean id="mySessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="myDataSource"/>
        <property name="mappingResources">
            <list>
                <value>product.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <value>
                hibernate.dialect=org.hibernate.dialect.HSQLDialect
            </value>
        </property>
    </bean>

</beans>
```

Switching from a local Jakarta Commons DBCP `BasicDataSource` to a JNDI-located`DataSource` (usually managed by an application server) is only a matter of
configuration, as the following example shows:

```
<beans>
    <jee:jndi-lookup id="myDataSource" jndi-name="java:comp/env/jdbc/myds"/>
</beans>
```

You can also access a JNDI-located `SessionFactory`, using Spring’s`JndiObjectFactoryBean` / `<jee:jndi-lookup>` to retrieve and expose it.
However, that is typically not common outside of an EJB context.

|   |Spring also provides a `LocalSessionFactoryBuilder` variant, seamlessly integrating<br/>with `@Bean` style configuration and programmatic setup (no `FactoryBean` involved).<br/><br/>Both `LocalSessionFactoryBean` and `LocalSessionFactoryBuilder` support background<br/>bootstrapping, with Hibernate initialization running in parallel to the application<br/>bootstrap thread on a given bootstrap executor (such as a `SimpleAsyncTaskExecutor`).<br/>On `LocalSessionFactoryBean`, this is available through the `bootstrapExecutor`property. On the programmatic `LocalSessionFactoryBuilder`, there is an overloaded`buildSessionFactory` method that takes a bootstrap executor argument.<br/><br/>As of Spring Framework 5.1, such a native Hibernate setup can also expose a JPA`EntityManagerFactory` for standard JPA interaction next to native Hibernate access.<br/>See [Native Hibernate Setup for JPA](#orm-jpa-hibernate) for details.|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

#### [](#orm-hibernate-straight)5.3.2. Implementing DAOs Based on the Plain Hibernate API ####

Hibernate has a feature called contextual sessions, wherein Hibernate itself manages
one current `Session` per transaction. This is roughly equivalent to Spring’s
synchronization of one Hibernate `Session` per transaction. A corresponding DAO
implementation resembles the following example, based on the plain Hibernate API:

Java

```
public class ProductDaoImpl implements ProductDao {

    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public Collection loadProductsByCategory(String category) {
        return this.sessionFactory.getCurrentSession()
                .createQuery("from test.Product product where product.category=?")
                .setParameter(0, category)
                .list();
    }
}
```

Kotlin

```
class ProductDaoImpl(private val sessionFactory: SessionFactory) : ProductDao {

    fun loadProductsByCategory(category: String): Collection<*> {
        return sessionFactory.currentSession
                .createQuery("from test.Product product where product.category=?")
                .setParameter(0, category)
                .list()
    }
}
```

This style is similar to that of the Hibernate reference documentation and examples,
except for holding the `SessionFactory` in an instance variable. We strongly recommend
such an instance-based setup over the old-school `static` `HibernateUtil` class from
Hibernate’s CaveatEmptor sample application. (In general, do not keep any resources in`static` variables unless absolutely necessary.)

The preceding DAO example follows the dependency injection pattern. It fits nicely into a Spring IoC
container, as it would if coded against Spring’s `HibernateTemplate`.
You can also set up such a DAO in plain Java (for example, in unit tests). To do so,
instantiate it and call `setSessionFactory(..)` with the desired factory reference. As a
Spring bean definition, the DAO would resemble the following:

```
<beans>

    <bean id="myProductDao" class="product.ProductDaoImpl">
        <property name="sessionFactory" ref="mySessionFactory"/>
    </bean>

</beans>
```

The main advantage of this DAO style is that it depends on Hibernate API only. No import
of any Spring class is required. This is appealing from a non-invasiveness
perspective and may feel more natural to Hibernate developers.

However, the DAO throws plain `HibernateException` (which is unchecked, so it does not have
to be declared or caught), which means that callers can treat exceptions only as being
generally fatal — unless they want to depend on Hibernate’s own exception hierarchy.
Catching specific causes (such as an optimistic locking failure) is not possible without
tying the caller to the implementation strategy. This trade off might be acceptable to
applications that are strongly Hibernate-based, do not need any special exception
treatment, or both.

Fortunately, Spring’s `LocalSessionFactoryBean` supports Hibernate’s`SessionFactory.getCurrentSession()` method for any Spring transaction strategy,
returning the current Spring-managed transactional `Session`, even with`HibernateTransactionManager`. The standard behavior of that method remains
to return the current `Session` associated with the ongoing JTA transaction, if any.
This behavior applies regardless of whether you use Spring’s`JtaTransactionManager`, EJB container managed transactions (CMTs), or JTA.

In summary, you can implement DAOs based on the plain Hibernate API, while still being
able to participate in Spring-managed transactions.

#### [](#orm-hibernate-tx-declarative)5.3.3. Declarative Transaction Demarcation ####

We recommend that you use Spring’s declarative transaction support, which lets you
replace explicit transaction demarcation API calls in your Java code with an AOP
transaction interceptor. You can configure this transaction interceptor in a Spring
container by using either Java annotations or XML. This declarative transaction capability
lets you keep business services free of repetitive transaction demarcation code and
focus on adding business logic, which is the real value of your application.

|   |Before you continue, we are strongly encourage you to read [Declarative Transaction Management](#transaction-declarative)if you have not already done so.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------|

You can annotate the service layer with `@Transactional` annotations and instruct the
Spring container to find these annotations and provide transactional semantics for
these annotated methods. The following example shows how to do so:

Java

```
public class ProductServiceImpl implements ProductService {

    private ProductDao productDao;

    public void setProductDao(ProductDao productDao) {
        this.productDao = productDao;
    }

    @Transactional
    public void increasePriceOfAllProductsInCategory(final String category) {
        List productsToChange = this.productDao.loadProductsByCategory(category);
        // ...
    }

    @Transactional(readOnly = true)
    public List<Product> findAllProducts() {
        return this.productDao.findAllProducts();
    }
}
```

Kotlin

```
class ProductServiceImpl(private val productDao: ProductDao) : ProductService {

    @Transactional
    fun increasePriceOfAllProductsInCategory(category: String) {
        val productsToChange = productDao.loadProductsByCategory(category)
        // ...
    }

    @Transactional(readOnly = true)
    fun findAllProducts() = productDao.findAllProducts()
}
```

In the container, you need to set up the `PlatformTransactionManager` implementation
(as a bean) and a `<tx:annotation-driven/>` entry, opting into `@Transactional`processing at runtime. The following example shows how to do so:

```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!-- SessionFactory, DataSource, etc. omitted -->

    <bean id="transactionManager"
            class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <tx:annotation-driven/>

    <bean id="myProductService" class="product.SimpleProductService">
        <property name="productDao" ref="myProductDao"/>
    </bean>

</beans>
```

#### [](#orm-hibernate-tx-programmatic)5.3.4. Programmatic Transaction Demarcation ####

You can demarcate transactions in a higher level of the application, on top of
lower-level data access services that span any number of operations. Nor do restrictions
exist on the implementation of the surrounding business service. It needs only a Spring`PlatformTransactionManager`. Again, the latter can come from anywhere, but preferably
as a bean reference through a `setTransactionManager(..)` method. Also, the`productDAO` should be set by a `setProductDao(..)` method. The following pair of snippets show
a transaction manager and a business service definition in a Spring application context
and an example for a business method implementation:

```
<beans>

    <bean id="myTxManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="mySessionFactory"/>
    </bean>

    <bean id="myProductService" class="product.ProductServiceImpl">
        <property name="transactionManager" ref="myTxManager"/>
        <property name="productDao" ref="myProductDao"/>
    </bean>

</beans>
```

Java

```
public class ProductServiceImpl implements ProductService {

    private TransactionTemplate transactionTemplate;
    private ProductDao productDao;

    public void setTransactionManager(PlatformTransactionManager transactionManager) {
        this.transactionTemplate = new TransactionTemplate(transactionManager);
    }

    public void setProductDao(ProductDao productDao) {
        this.productDao = productDao;
    }

    public void increasePriceOfAllProductsInCategory(final String category) {
        this.transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            public void doInTransactionWithoutResult(TransactionStatus status) {
                List productsToChange = this.productDao.loadProductsByCategory(category);
                // do the price increase...
            }
        });
    }
}
```

Kotlin

```
class ProductServiceImpl(transactionManager: PlatformTransactionManager,
                        private val productDao: ProductDao) : ProductService {

    private val transactionTemplate = TransactionTemplate(transactionManager)

    fun increasePriceOfAllProductsInCategory(category: String) {
        transactionTemplate.execute {
            val productsToChange = productDao.loadProductsByCategory(category)
            // do the price increase...
        }
    }
}
```

Spring’s `TransactionInterceptor` lets any checked application exception be thrown
with the callback code, while `TransactionTemplate` is restricted to unchecked
exceptions within the callback. `TransactionTemplate` triggers a rollback in case of
an unchecked application exception or if the transaction is marked rollback-only by
the application (by setting `TransactionStatus`). By default, `TransactionInterceptor`behaves the same way but allows configurable rollback policies per method.

#### [](#orm-hibernate-tx-strategies)5.3.5. Transaction Management Strategies ####

Both `TransactionTemplate` and `TransactionInterceptor` delegate the actual transaction
handling to a `PlatformTransactionManager` instance (which can be a`HibernateTransactionManager` (for a single Hibernate `SessionFactory`) by using a`ThreadLocal` `Session` under the hood) or a `JtaTransactionManager` (delegating to the
JTA subsystem of the container) for Hibernate applications. You can even use a custom`PlatformTransactionManager` implementation. Switching from native Hibernate transaction
management to JTA (such as when facing distributed transaction requirements for certain
deployments of your application) is only a matter of configuration. You can replace
the Hibernate transaction manager with Spring’s JTA transaction implementation. Both
transaction demarcation and data access code work without changes, because they
use the generic transaction management APIs.

For distributed transactions across multiple Hibernate session factories, you can combine`JtaTransactionManager` as a transaction strategy with multiple`LocalSessionFactoryBean` definitions. Each DAO then gets one specific `SessionFactory`reference passed into its corresponding bean property. If all underlying JDBC data
sources are transactional container ones, a business service can demarcate transactions
across any number of DAOs and any number of session factories without special regard, as
long as it uses `JtaTransactionManager` as the strategy.

Both `HibernateTransactionManager` and `JtaTransactionManager` allow for proper
JVM-level cache handling with Hibernate, without container-specific transaction manager
lookup or a JCA connector (if you do not use EJB to initiate transactions).

`HibernateTransactionManager` can export the Hibernate JDBC `Connection` to plain JDBC
access code for a specific `DataSource`. This ability allows for high-level
transaction demarcation with mixed Hibernate and JDBC data access completely without
JTA, provided you access only one database. `HibernateTransactionManager` automatically
exposes the Hibernate transaction as a JDBC transaction if you have set up the passed-in`SessionFactory` with a `DataSource` through the `dataSource` property of the`LocalSessionFactoryBean` class. Alternatively, you can specify explicitly the`DataSource` for which the transactions are supposed to be exposed through the`dataSource` property of the `HibernateTransactionManager` class.

#### [](#orm-hibernate-resources)5.3.6. Comparing Container-managed and Locally Defined Resources ####

You can switch between a container-managed JNDI `SessionFactory` and a locally defined
one without having to change a single line of application code. Whether to keep
resource definitions in the container or locally within the application is mainly a
matter of the transaction strategy that you use. Compared to a Spring-defined local`SessionFactory`, a manually registered JNDI `SessionFactory` does not provide any
benefits. Deploying a `SessionFactory` through Hibernate’s JCA connector provides the
added value of participating in the Java EE server’s management infrastructure, but does
not add actual value beyond that.

Spring’s transaction support is not bound to a container. When configured with any strategy
other than JTA, transaction support also works in a stand-alone or test environment.
Especially in the typical case of single-database transactions, Spring’s single-resource
local transaction support is a lightweight and powerful alternative to JTA. When you use
local EJB stateless session beans to drive transactions, you depend both on an EJB
container and on JTA, even if you access only a single database and use only stateless
session beans to provide declarative transactions through container-managed
transactions. Direct use of JTA programmatically also requires a Java EE environment.
JTA does not involve only container dependencies in terms of JTA itself and of
JNDI `DataSource` instances. For non-Spring, JTA-driven Hibernate transactions, you have
to use the Hibernate JCA connector or extra Hibernate transaction code with the`TransactionManagerLookup` configured for proper JVM-level caching.

Spring-driven transactions can work as well with a locally defined Hibernate`SessionFactory` as they do with a local JDBC `DataSource`, provided they access a
single database. Thus, you need only use Spring’s JTA transaction strategy when you
have distributed transaction requirements. A JCA connector requires container-specific
deployment steps, and (obviously) JCA support in the first place. This configuration
requires more work than deploying a simple web application with local resource
definitions and Spring-driven transactions. Also, you often need the Enterprise Edition
of your container if you use, for example, WebLogic Express, which does not
provide JCA. A Spring application with local resources and transactions that span one
single database works in any Java EE web container (without JTA, JCA, or EJB), such as
Tomcat, Resin, or even plain Jetty. Additionally, you can easily reuse such a middle
tier in desktop applications or test suites.

All things considered, if you do not use EJBs, stick with local `SessionFactory` setup
and Spring’s `HibernateTransactionManager` or `JtaTransactionManager`. You get all of
the benefits, including proper transactional JVM-level caching and distributed
transactions, without the inconvenience of container deployment. JNDI registration of a
Hibernate `SessionFactory` through the JCA connector adds value only when used in
conjunction with EJBs.

#### [](#orm-hibernate-invalid-jdbc-access-error)5.3.7. Spurious Application Server Warnings with Hibernate ####

In some JTA environments with very strict `XADataSource` implementations (currently
some WebLogic Server and WebSphere versions), when Hibernate is configured without
regard to the JTA transaction manager for that environment, spurious warnings or
exceptions can show up in the application server log. These warnings or exceptions
indicate that the connection being accessed is no longer valid or JDBC access is no
longer valid, possibly because the transaction is no longer active. As an example,
here is an actual exception from WebLogic:

```
java.sql.SQLException: The transaction is no longer active - status: 'Committed'. No
further JDBC access is allowed within this transaction.
```

Another common problem is a connection leak after JTA transactions, with Hibernate
sessions (and potentially underlying JDBC connections) not getting closed properly.

You can resolve such issues by making Hibernate aware of the JTA transaction manager,
to which it synchronizes (along with Spring). You have two options for doing this:

* Pass your Spring `JtaTransactionManager` bean to your Hibernate setup. The easiest
  way is a bean reference into the `jtaTransactionManager` property for your`LocalSessionFactoryBean` bean (see [Hibernate Transaction Setup](#transaction-strategies-hibernate)).
  Spring then makes the corresponding JTA strategies available to Hibernate.

* You may also configure Hibernate’s JTA-related properties explicitly, in particular
  "hibernate.transaction.coordinator\_class", "hibernate.connection.handling\_mode"
  and potentially "hibernate.transaction.jta.platform" in your "hibernateProperties"
  on `LocalSessionFactoryBean` (see Hibernate’s manual for details on those properties).

The remainder of this section describes the sequence of events that occur with and
without Hibernate’s awareness of the JTA `PlatformTransactionManager`.

When Hibernate is not configured with any awareness of the JTA transaction manager,
the following events occur when a JTA transaction commits:

* The JTA transaction commits.

* Spring’s `JtaTransactionManager` is synchronized to the JTA transaction, so it is
  called back through an `afterCompletion` callback by the JTA transaction manager.

* Among other activities, this synchronization can trigger a callback by Spring to
  Hibernate, through Hibernate’s `afterTransactionCompletion` callback (used to clear
  the Hibernate cache), followed by an explicit `close()` call on the Hibernate session,
  which causes Hibernate to attempt to `close()` the JDBC Connection.

* In some environments, this `Connection.close()` call then triggers the warning or
  error, as the application server no longer considers the `Connection` to be usable,
  because the transaction has already been committed.

When Hibernate is configured with awareness of the JTA transaction manager,
the following events occur when a JTA transaction commits:

* The JTA transaction is ready to commit.

* Spring’s `JtaTransactionManager` is synchronized to the JTA transaction, so the
  transaction is called back through a `beforeCompletion` callback by the JTA
  transaction manager.

* Spring is aware that Hibernate itself is synchronized to the JTA transaction and
  behaves differently than in the previous scenario. In particular, it aligns with
  Hibernate’s transactional resource management.

* The JTA transaction commits.

* Hibernate is synchronized to the JTA transaction, so the transaction is called back
  through an `afterCompletion` callback by the JTA transaction manager and can
  properly clear its cache.

### [](#orm-jpa)5.4. JPA ###

The Spring JPA, available under the `org.springframework.orm.jpa` package, offers
comprehensive support for the[Java Persistence
API](https://www.oracle.com/technetwork/articles/javaee/jpa-137156.html) in a manner similar to the integration with Hibernate while being aware of
the underlying implementation in order to provide additional features.

#### [](#orm-jpa-setup)5.4.1. Three Options for JPA Setup in a Spring Environment ####

The Spring JPA support offers three ways of setting up the JPA `EntityManagerFactory`that is used by the application to obtain an entity manager.

* [Using `LocalEntityManagerFactoryBean`](#orm-jpa-setup-lemfb)

* [Obtaining an EntityManagerFactory from JNDI](#orm-jpa-setup-jndi)

* [Using `LocalContainerEntityManagerFactoryBean`](#orm-jpa-setup-lcemfb)

##### [](#orm-jpa-setup-lemfb)Using `LocalEntityManagerFactoryBean` #####

You can use this option only in simple deployment environments such as stand-alone
applications and integration tests.

The `LocalEntityManagerFactoryBean` creates an `EntityManagerFactory` suitable for
simple deployment environments where the application uses only JPA for data access.
The factory bean uses the JPA `PersistenceProvider` auto-detection mechanism (according
to JPA’s Java SE bootstrapping) and, in most cases, requires you to specify only the
persistence unit name. The following XML example configures such a bean:

```
<beans>
    <bean id="myEmf" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="myPersistenceUnit"/>
    </bean>
</beans>
```

This form of JPA deployment is the simplest and the most limited. You cannot refer to an
existing JDBC `DataSource` bean definition, and no support for global transactions
exists. Furthermore, weaving (byte-code transformation) of persistent classes is
provider-specific, often requiring a specific JVM agent to be specified on startup. This
option is sufficient only for stand-alone applications and test environments, for which
the JPA specification is designed.

##### [](#orm-jpa-setup-jndi)Obtaining an EntityManagerFactory from JNDI #####

You can use this option when deploying to a Java EE server. Check your server’s documentation
on how to deploy a custom JPA provider into your server, allowing for a different
provider than the server’s default.

Obtaining an `EntityManagerFactory` from JNDI (for example in a Java EE environment),
is a matter of changing the XML configuration, as the following example shows:

```
<beans>
    <jee:jndi-lookup id="myEmf" jndi-name="persistence/myPersistenceUnit"/>
</beans>
```

This action assumes standard Java EE bootstrapping. The Java EE server auto-detects
persistence units (in effect, `META-INF/persistence.xml` files in application jars) and`persistence-unit-ref` entries in the Java EE deployment descriptor (for example,`web.xml`) and defines environment naming context locations for those persistence units.

In such a scenario, the entire persistence unit deployment, including the weaving
(byte-code transformation) of persistent classes, is up to the Java EE server. The JDBC`DataSource` is defined through a JNDI location in the `META-INF/persistence.xml` file.`EntityManager` transactions are integrated with the server’s JTA subsystem. Spring merely
uses the obtained `EntityManagerFactory`, passing it on to application objects through
dependency injection and managing transactions for the persistence unit (typically
through `JtaTransactionManager`).

If you use multiple persistence units in the same application, the bean names of such
JNDI-retrieved persistence units should match the persistence unit names that the
application uses to refer to them (for example, in `@PersistenceUnit` and`@PersistenceContext` annotations).

##### [](#orm-jpa-setup-lcemfb)Using `LocalContainerEntityManagerFactoryBean` #####

You can use this option for full JPA capabilities in a Spring-based application environment.
This includes web containers such as Tomcat, stand-alone applications, and
integration tests with sophisticated persistence requirements.

|   |If you want to specifically configure a Hibernate setup, an immediate alternative<br/>is to set up a native Hibernate `LocalSessionFactoryBean` instead of a plain JPA`LocalContainerEntityManagerFactoryBean`, letting it interact with JPA access code<br/>as well as native Hibernate access code.<br/>See [Native Hibernate setup for JPA interaction](#orm-jpa-hibernate) for details.|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

The `LocalContainerEntityManagerFactoryBean` gives full control over`EntityManagerFactory` configuration and is appropriate for environments where
fine-grained customization is required. The `LocalContainerEntityManagerFactoryBean`creates a `PersistenceUnitInfo` instance based on the `persistence.xml` file, the
supplied `dataSourceLookup` strategy, and the specified `loadTimeWeaver`. It is, thus,
possible to work with custom data sources outside of JNDI and to control the weaving
process. The following example shows a typical bean definition for a`LocalContainerEntityManagerFactoryBean`:

```
<beans>
    <bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="someDataSource"/>
        <property name="loadTimeWeaver">
            <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
        </property>
    </bean>
</beans>
```

The following example shows a typical `persistence.xml` file:

```
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
    <persistence-unit name="myUnit" transaction-type="RESOURCE_LOCAL">
        <mapping-file>META-INF/orm.xml</mapping-file>
        <exclude-unlisted-classes/>
    </persistence-unit>
</persistence>
```

|   |The `<exclude-unlisted-classes/>` shortcut indicates that no scanning for<br/>annotated entity classes is supposed to occur. An explicit 'true' value<br/>(`<exclude-unlisted-classes>true</exclude-unlisted-classes/>`) also means no scan.`<exclude-unlisted-classes>false</exclude-unlisted-classes/>` does trigger a scan.<br/>However, we recommend omitting the `exclude-unlisted-classes` element<br/>if you want entity class scanning to occur.|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

Using the `LocalContainerEntityManagerFactoryBean` is the most powerful JPA setup
option, allowing for flexible local configuration within the application. It supports
links to an existing JDBC `DataSource`, supports both local and global transactions, and
so on. However, it also imposes requirements on the runtime environment, such as the
availability of a weaving-capable class loader if the persistence provider demands
byte-code transformation.

This option may conflict with the built-in JPA capabilities of a Java EE server. In a
full Java EE environment, consider obtaining your `EntityManagerFactory` from JNDI.
Alternatively, specify a custom `persistenceXmlLocation` on your`LocalContainerEntityManagerFactoryBean` definition (for example,
META-INF/my-persistence.xml) and include only a descriptor with that name in your
application jar files. Because the Java EE server looks only for default`META-INF/persistence.xml` files, it ignores such custom persistence units and, hence,
avoids conflicts with a Spring-driven JPA setup upfront. (This applies to Resin 3.1, for
example.)

When is load-time weaving required?

Not all JPA providers require a JVM agent. Hibernate is an example of one that does not.
If your provider does not require an agent or you have other alternatives, such as
applying enhancements at build time through a custom compiler or an Ant task, you should not use the
load-time weaver.

The `LoadTimeWeaver` interface is a Spring-provided class that lets JPA`ClassTransformer` instances be plugged in a specific manner, depending on whether the
environment is a web container or application server. Hooking `ClassTransformers`through an[agent](https://docs.oracle.com/javase/6/docs/api/java/lang/instrument/package-summary.html)is typically not efficient. The agents work against the entire virtual machine and
inspect every class that is loaded, which is usually undesirable in a production
server environment.

Spring provides a number of `LoadTimeWeaver` implementations for various environments,
letting `ClassTransformer` instances be applied only for each class loader and not
for each VM.

See the [Spring configuration](core.html#aop-aj-ltw-spring) in the AOP chapter for
more insight regarding the `LoadTimeWeaver` implementations and their setup, either
generic or customized to various platforms (such as Tomcat, JBoss and WebSphere).

As described in [Spring configuration](core.html#aop-aj-ltw-spring), you can configure
a context-wide `LoadTimeWeaver` by using the `@EnableLoadTimeWeaving` annotation or the`context:load-time-weaver` XML element. Such a global weaver is automatically picked up
by all JPA `LocalContainerEntityManagerFactoryBean` instances. The following example
shows the preferred way of setting up a load-time weaver, delivering auto-detection
of the platform (e.g. Tomcat’s weaving-capable class loader or Spring’s JVM agent)
and automatic propagation of the weaver to all weaver-aware beans:

```
<context:load-time-weaver/>
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    ...
</bean>
```

However, you can, if needed, manually specify a dedicated weaver through the`loadTimeWeaver` property, as the following example shows:

```
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="loadTimeWeaver">
        <bean class="org.springframework.instrument.classloading.ReflectiveLoadTimeWeaver"/>
    </property>
</bean>
```

No matter how the LTW is configured, by using this technique, JPA applications relying on
instrumentation can run in the target platform (for example, Tomcat) without needing an agent.
This is especially important when the hosting applications rely on different JPA
implementations, because the JPA transformers are applied only at the class-loader level and
are, thus, isolated from each other.

##### [](#orm-jpa-setup-multiple)Dealing with Multiple Persistence Units #####

For applications that rely on multiple persistence units locations (stored in various
JARS in the classpath, for example), Spring offers the `PersistenceUnitManager` to act as
a central repository and to avoid the persistence units discovery process, which can be
expensive. The default implementation lets multiple locations be specified. These locations are
parsed and later retrieved through the persistence unit name. (By default, the classpath
is searched for `META-INF/persistence.xml` files.) The following example configures
multiple locations:

```
<bean id="pum" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
    <property name="persistenceXmlLocations">
        <list>
            <value>org/springframework/orm/jpa/domain/persistence-multi.xml</value>
            <value>classpath:/my/package/**/custom-persistence.xml</value>
            <value>classpath*:META-INF/persistence.xml</value>
        </list>
    </property>
    <property name="dataSources">
        <map>
            <entry key="localDataSource" value-ref="local-db"/>
            <entry key="remoteDataSource" value-ref="remote-db"/>
        </map>
    </property>
    <!-- if no datasource is specified, use this one -->
    <property name="defaultDataSource" ref="remoteDataSource"/>
</bean>

<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceUnitManager" ref="pum"/>
    <property name="persistenceUnitName" value="myCustomUnit"/>
</bean>
```

The default implementation allows customization of the `PersistenceUnitInfo` instances
(before they are fed to the JPA provider) either declaratively (through its properties, which
affect all hosted units) or programmatically (through the`PersistenceUnitPostProcessor`, which allows persistence unit selection). If no`PersistenceUnitManager` is specified, one is created and used internally by`LocalContainerEntityManagerFactoryBean`.

##### [](#orm-jpa-setup-background)Background Bootstrapping #####

`LocalContainerEntityManagerFactoryBean` supports background bootstrapping through
the `bootstrapExecutor` property, as the following example shows:

```
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="bootstrapExecutor">
        <bean class="org.springframework.core.task.SimpleAsyncTaskExecutor"/>
    </property>
</bean>
```

The actual JPA provider bootstrapping is handed off to the specified executor and then,
running in parallel, to the application bootstrap thread. The exposed `EntityManagerFactory`proxy can be injected into other application components and is even able to respond to`EntityManagerFactoryInfo` configuration inspection. However, once the actual JPA provider
is being accessed by other components (for example, calling `createEntityManager`), those calls
block until the background bootstrapping has completed. In particular, when you use
Spring Data JPA, make sure to set up deferred bootstrapping for its repositories as well.

#### [](#orm-jpa-dao)5.4.2. Implementing DAOs Based on JPA: `EntityManagerFactory` and `EntityManager` ####

|   |Although `EntityManagerFactory` instances are thread-safe, `EntityManager` instances are<br/>not. The injected JPA `EntityManager` behaves like an `EntityManager` fetched from an<br/>application server’s JNDI environment, as defined by the JPA specification. It delegates<br/>all calls to the current transactional `EntityManager`, if any. Otherwise, it falls back<br/>to a newly created `EntityManager` per operation, in effect making its usage thread-safe.|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

It is possible to write code against the plain JPA without any Spring dependencies, by
using an injected `EntityManagerFactory` or `EntityManager`. Spring can understand the`@PersistenceUnit` and `@PersistenceContext` annotations both at the field and the method level
if a `PersistenceAnnotationBeanPostProcessor` is enabled. The following example shows a plain JPA DAO implementation
that uses the `@PersistenceUnit` annotation:

Java

```
public class ProductDaoImpl implements ProductDao {

    private EntityManagerFactory emf;

    @PersistenceUnit
    public void setEntityManagerFactory(EntityManagerFactory emf) {
        this.emf = emf;
    }

    public Collection loadProductsByCategory(String category) {
        EntityManager em = this.emf.createEntityManager();
        try {
            Query query = em.createQuery("from Product as p where p.category = ?1");
            query.setParameter(1, category);
            return query.getResultList();
        }
        finally {
            if (em != null) {
                em.close();
            }
        }
    }
}
```

Kotlin

```
class ProductDaoImpl : ProductDao {

    private lateinit var emf: EntityManagerFactory

    @PersistenceUnit
    fun setEntityManagerFactory(emf: EntityManagerFactory) {
        this.emf = emf
    }

    fun loadProductsByCategory(category: String): Collection<*> {
        val em = this.emf.createEntityManager()
        val query = em.createQuery("from Product as p where p.category = ?1");
        query.setParameter(1, category);
        return query.resultList;
    }
}
```

The preceding DAO has no dependency on Spring and still fits nicely into a Spring
application context. Moreover, the DAO takes advantage of annotations to require the
injection of the default `EntityManagerFactory`, as the following example bean definition shows:

```
<beans>

    <!-- bean post-processor for JPA annotations -->
    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>

    <bean id="myProductDao" class="product.ProductDaoImpl"/>

</beans>
```

As an alternative to explicitly defining a `PersistenceAnnotationBeanPostProcessor`,
consider using the Spring `context:annotation-config` XML element in your application
context configuration. Doing so automatically registers all Spring standard
post-processors for annotation-based configuration, including`CommonAnnotationBeanPostProcessor` and so on.

Consider the following example:

```
<beans>

    <!-- post-processors for all standard config annotations -->
    <context:annotation-config/>

    <bean id="myProductDao" class="product.ProductDaoImpl"/>

</beans>
```

The main problem with such a DAO is that it always creates a new `EntityManager` through
the factory. You can avoid this by requesting a transactional `EntityManager` (also
called a “shared EntityManager” because it is a shared, thread-safe proxy for the actual
transactional EntityManager) to be injected instead of the factory. The following example shows how to do so:

Java

```
public class ProductDaoImpl implements ProductDao {

    @PersistenceContext
    private EntityManager em;

    public Collection loadProductsByCategory(String category) {
        Query query = em.createQuery("from Product as p where p.category = :category");
        query.setParameter("category", category);
        return query.getResultList();
    }
}
```

Kotlin

```
class ProductDaoImpl : ProductDao {

    @PersistenceContext
    private lateinit var em: EntityManager

    fun loadProductsByCategory(category: String): Collection<*> {
        val query = em.createQuery("from Product as p where p.category = :category")
        query.setParameter("category", category)
        return query.resultList
    }
}
```

The `@PersistenceContext` annotation has an optional attribute called `type`, which defaults to`PersistenceContextType.TRANSACTION`. You can use this default to receive a shared`EntityManager` proxy. The alternative, `PersistenceContextType.EXTENDED`, is a completely
different affair. This results in a so-called extended `EntityManager`, which is not
thread-safe and, hence, must not be used in a concurrently accessed component, such as a
Spring-managed singleton bean. Extended `EntityManager` instances are only supposed to be used in
stateful components that, for example, reside in a session, with the lifecycle of the`EntityManager` not tied to a current transaction but rather being completely up to the
application.

Method- and field-level Injection

You can apply annotations that indicate dependency injections (such as `@PersistenceUnit` and`@PersistenceContext`) on field or methods inside a class — hence the
expressions “method-level injection” and “field-level injection”. Field-level
annotations are concise and easier to use while method-level annotations allow for further
processing of the injected dependency. In both cases, the member visibility (public,
protected, or private) does not matter.

What about class-level annotations?

On the Java EE platform, they are used for dependency declaration and not for resource
injection.

The injected `EntityManager` is Spring-managed (aware of the ongoing transaction).
Even though the new DAO implementation uses method-level
injection of an `EntityManager` instead of an `EntityManagerFactory`, no change is
required in the application context XML, due to annotation usage.

The main advantage of this DAO style is that it depends only on the Java Persistence API.
No import of any Spring class is required. Moreover, as the JPA annotations are understood,
the injections are applied automatically by the Spring container. This is appealing from
a non-invasiveness perspective and can feel more natural to JPA developers.

#### [](#orm-jpa-tx)5.4.3. Spring-driven JPA transactions ####

|   |We strongly encourage you to read [Declarative Transaction Management](#transaction-declarative), if you have not<br/>already done so, to get more detailed coverage of Spring’s declarative transaction support.|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

The recommended strategy for JPA is local transactions through JPA’s native transaction
support. Spring’s `JpaTransactionManager` provides many capabilities known from local
JDBC transactions (such as transaction-specific isolation levels and resource-level
read-only optimizations) against any regular JDBC connection pool (no XA requirement).

Spring JPA also lets a configured `JpaTransactionManager` expose a JPA transaction
to JDBC access code that accesses the same `DataSource`, provided that the registered`JpaDialect` supports retrieval of the underlying JDBC `Connection`.
Spring provides dialects for the EclipseLink and Hibernate JPA implementations.
See the [next section](#orm-jpa-dialect) for details on the `JpaDialect` mechanism.

|   |As an immediate alternative, Spring’s native `HibernateTransactionManager` is capable<br/>of interacting with JPA access code, adapting to several Hibernate specifics and providing<br/>JDBC interaction. This makes particular sense in combination with `LocalSessionFactoryBean`setup. See [Native Hibernate Setup for JPA Interaction](#orm-jpa-hibernate) for details.|
|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

#### [](#orm-jpa-dialect)5.4.4. Understanding `JpaDialect` and `JpaVendorAdapter` ####

As an advanced feature, `JpaTransactionManager` and subclasses of`AbstractEntityManagerFactoryBean` allow a custom `JpaDialect` to be passed into the`jpaDialect` bean property. A `JpaDialect` implementation can enable the following advanced
features supported by Spring, usually in a vendor-specific manner:

* Applying specific transaction semantics (such as custom isolation level or transaction
  timeout)

* Retrieving the transactional JDBC `Connection` (for exposure to JDBC-based DAOs)

* Advanced translation of `PersistenceExceptions` to Spring `DataAccessExceptions`

This is particularly valuable for special transaction semantics and for advanced
translation of exception. The default implementation (`DefaultJpaDialect`) does
not provide any special abilities and, if the features listed earlier are required, you have
to specify the appropriate dialect.

|   |As an even broader provider adaptation facility primarily for Spring’s full-featured`LocalContainerEntityManagerFactoryBean` setup, `JpaVendorAdapter` combines the<br/>capabilities of `JpaDialect` with other provider-specific defaults. Specifying a`HibernateJpaVendorAdapter` or `EclipseLinkJpaVendorAdapter` is the most convenient<br/>way of auto-configuring an `EntityManagerFactory` setup for Hibernate or EclipseLink,<br/>respectively. Note that those provider adapters are primarily designed for use with<br/>Spring-driven transaction management (that is, for use with `JpaTransactionManager`).|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

See the [`JpaDialect`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/orm/jpa/JpaDialect.html) and[`JpaVendorAdapter`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/orm/jpa/JpaVendorAdapter.html) javadoc for
more details of its operations and how they are used within Spring’s JPA support.

#### [](#orm-jpa-jta)5.4.5. Setting up JPA with JTA Transaction Management ####

As an alternative to `JpaTransactionManager`, Spring also allows for multi-resource
transaction coordination through JTA, either in a Java EE environment or with a
stand-alone transaction coordinator, such as Atomikos. Aside from choosing Spring’s`JtaTransactionManager` instead of `JpaTransactionManager`, you need to take few further
steps:

* The underlying JDBC connection pools need to be XA-capable and be integrated with
  your transaction coordinator. This is usually straightforward in a Java EE environment,
  exposing a different kind of `DataSource` through JNDI. See your application server
  documentation for details. Analogously, a standalone transaction coordinator usually
  comes with special XA-integrated `DataSource` variants. Again, check its documentation.

* The JPA `EntityManagerFactory` setup needs to be configured for JTA. This is
  provider-specific, typically through special properties to be specified as `jpaProperties`on `LocalContainerEntityManagerFactoryBean`. In the case of Hibernate, these properties
  are even version-specific. See your Hibernate documentation for details.

* Spring’s `HibernateJpaVendorAdapter` enforces certain Spring-oriented defaults, such
  as the connection release mode, `on-close`, which matches Hibernate’s own default in
  Hibernate 5.0 but not any more in Hibernate 5.1+. For a JTA setup, make sure to declare
  your persistence unit transaction type as "JTA". Alternatively, set Hibernate 5.2’s`hibernate.connection.handling_mode` property to`DELAYED_ACQUISITION_AND_RELEASE_AFTER_STATEMENT` to restore Hibernate’s own default.
  See [Spurious Application Server Warnings with Hibernate](#orm-hibernate-invalid-jdbc-access-error) for related notes.

* Alternatively, consider obtaining the `EntityManagerFactory` from your application
  server itself (that is, through a JNDI lookup instead of a locally declared`LocalContainerEntityManagerFactoryBean`). A server-provided `EntityManagerFactory`might require special definitions in your server configuration (making the deployment
  less portable) but is set up for the server’s JTA environment.

#### [](#orm-jpa-hibernate)5.4.6. Native Hibernate Setup and Native Hibernate Transactions for JPA Interaction ####

A native `LocalSessionFactoryBean` setup in combination with `HibernateTransactionManager`allows for interaction with `@PersistenceContext` and other JPA access code. A Hibernate`SessionFactory` natively implements JPA’s `EntityManagerFactory` interface now
and a Hibernate `Session` handle natively is a JPA `EntityManager`.
Spring’s JPA support facilities automatically detect native Hibernate sessions.

Such native Hibernate setup can, therefore, serve as a replacement for a standard JPA`LocalContainerEntityManagerFactoryBean` and `JpaTransactionManager` combination
in many scenarios, allowing for interaction with `SessionFactory.getCurrentSession()`(and also `HibernateTemplate`) next to `@PersistenceContext EntityManager` within
the same local transaction. Such a setup also provides stronger Hibernate integration
and more configuration flexibility, because it is not constrained by JPA bootstrap contracts.

You do not need `HibernateJpaVendorAdapter` configuration in such a scenario,
since Spring’s native Hibernate setup provides even more features
(for example, custom Hibernate Integrator setup, Hibernate 5.3 bean container integration,
and stronger optimizations for read-only transactions). Last but not least, you can also
express native Hibernate setup through `LocalSessionFactoryBuilder`,
seamlessly integrating with `@Bean` style configuration (no `FactoryBean` involved).

|   |`LocalSessionFactoryBean` and `LocalSessionFactoryBuilder` support background<br/>bootstrapping, just as the JPA `LocalContainerEntityManagerFactoryBean` does.<br/>See [Background Bootstrapping](#orm-jpa-setup-background) for an introduction.<br/><br/>On `LocalSessionFactoryBean`, this is available through the `bootstrapExecutor`property. On the programmatic `LocalSessionFactoryBuilder`, an overloaded`buildSessionFactory` method takes a bootstrap executor argument.|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

[](#oxm)6. Marshalling XML by Using Object-XML Mappers
----------

### [](#oxm-introduction)6.1. Introduction ###

This chapter, describes Spring’s Object-XML Mapping support. Object-XML
Mapping (O-X mapping for short) is the act of converting an XML document to and from
an object. This conversion process is also known as XML Marshalling, or XML
Serialization. This chapter uses these terms interchangeably.

Within the field of O-X mapping, a marshaller is responsible for serializing an
object (graph) to XML. In similar fashion, an unmarshaller deserializes the XML to
an object graph. This XML can take the form of a DOM document, an input or output
stream, or a SAX handler.

Some of the benefits of using Spring for your O/X mapping needs are:

* [Ease of configuration](#oxm-ease-of-configuration)

* [Consistent Interfaces](#oxm-consistent-interfaces)

* [Consistent Exception Hierarchy](#oxm-consistent-exception-hierarchy)

#### [](#oxm-ease-of-configuration)6.1.1. Ease of configuration ####

Spring’s bean factory makes it easy to configure marshallers, without needing to
construct JAXB context, JiBX binding factories, and so on. You can configure the marshallers
as you would any other bean in your application context. Additionally, XML namespace-based
configuration is available for a number of marshallers, making the configuration even
simpler.

#### [](#oxm-consistent-interfaces)6.1.2. Consistent Interfaces ####

Spring’s O-X mapping operates through two global interfaces: [`Marshaller`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/oxm/Marshaller.html) and[`Unmarshaller`](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/oxm/Unmarshaller.html). These abstractions let you switch O-X mapping frameworks
with relative ease, with little or no change required on the classes that do the
marshalling. This approach has the additional benefit of making it possible to do XML
marshalling with a mix-and-match approach (for example, some marshalling performed using JAXB
and some by XStream) in a non-intrusive fashion, letting you use the strength of each
technology.

#### [](#oxm-consistent-exception-hierarchy)6.1.3. Consistent Exception Hierarchy ####

Spring provides a conversion from exceptions from the underlying O-X mapping tool to its
own exception hierarchy with the `XmlMappingException` as the root exception.
These runtime exceptions wrap the original exception so that no information is lost.

### [](#oxm-marshaller-unmarshaller)6.2. `Marshaller` and `Unmarshaller` ###

As stated in the [introduction](#oxm-introduction), a marshaller serializes an object
to XML, and an unmarshaller deserializes XML stream to an object. This section describes
the two Spring interfaces used for this purpose.

#### [](#oxm-marshaller)6.2.1. Understanding `Marshaller` ####

Spring abstracts all marshalling operations behind the`org.springframework.oxm.Marshaller` interface, the main method of which follows:

```
public interface Marshaller {

    /**
     * Marshal the object graph with the given root into the provided Result.
     */
    void marshal(Object graph, Result result) throws XmlMappingException, IOException;
}
```

The `Marshaller` interface has one main method, which marshals the given object to a
given `javax.xml.transform.Result`. The result is a tagging interface that basically
represents an XML output abstraction. Concrete implementations wrap various XML
representations, as the following table indicates:

|Result implementation|                 Wraps XML representation                  |
|---------------------|-----------------------------------------------------------|
|     `DOMResult`     |                    `org.w3c.dom.Node`                     |
|     `SAXResult`     |               `org.xml.sax.ContentHandler`                |
|   `StreamResult`    |`java.io.File`, `java.io.OutputStream`, or `java.io.Writer`|

|   |Although the `marshal()` method accepts a plain object as its first parameter, most`Marshaller` implementations cannot handle arbitrary objects. Instead, an object class<br/>must be mapped in a mapping file, be marked with an annotation, be registered with the<br/>marshaller, or have a common base class. Refer to the later sections in this chapter<br/>to determine how your O-X technology manages this.|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

#### [](#oxm-unmarshaller)6.2.2. Understanding `Unmarshaller` ####

Similar to the `Marshaller`, we have the `org.springframework.oxm.Unmarshaller`interface, which the following listing shows:

```
public interface Unmarshaller {

    /**
     * Unmarshal the given provided Source into an object graph.
     */
    Object unmarshal(Source source) throws XmlMappingException, IOException;
}
```

This interface also has one method, which reads from the given`javax.xml.transform.Source` (an XML input abstraction) and returns the object read. As
with `Result`, `Source` is a tagging interface that has three concrete implementations. Each
wraps a different XML representation, as the following table indicates:

|Source implementation|                 Wraps XML representation                 |
|---------------------|----------------------------------------------------------|
|     `DOMSource`     |                    `org.w3c.dom.Node`                    |
|     `SAXSource`     |  `org.xml.sax.InputSource`, and `org.xml.sax.XMLReader`  |
|   `StreamSource`    |`java.io.File`, `java.io.InputStream`, or `java.io.Reader`|

Even though there are two separate marshalling interfaces (`Marshaller` and`Unmarshaller`), all implementations in Spring-WS implement both in one class.
This means that you can wire up one marshaller class and refer to it both as a
marshaller and as an unmarshaller in your `applicationContext.xml`.

#### [](#oxm-xmlmappingexception)6.2.3. Understanding `XmlMappingException` ####

Spring converts exceptions from the underlying O-X mapping tool to its own exception
hierarchy with the `XmlMappingException` as the root exception.
These runtime exceptions wrap the original exception so that no information will be lost.

Additionally, the `MarshallingFailureException` and `UnmarshallingFailureException`provide a distinction between marshalling and unmarshalling operations, even though the
underlying O-X mapping tool does not do so.

The O-X Mapping exception hierarchy is shown in the following figure:

![oxm exceptions](images/oxm-exceptions.png)

### [](#oxm-usage)6.3. Using `Marshaller` and `Unmarshaller` ###

You can use Spring’s OXM for a wide variety of situations. In the following example, we
use it to marshal the settings of a Spring-managed application as an XML file. In the following example, we
use a simple JavaBean to represent the settings:

Java

```
public class Settings {

    private boolean fooEnabled;

    public boolean isFooEnabled() {
        return fooEnabled;
    }

    public void setFooEnabled(boolean fooEnabled) {
        this.fooEnabled = fooEnabled;
    }
}
```

Kotlin

```
class Settings {
    var isFooEnabled: Boolean = false
}
```

The application class uses this bean to store its settings. Besides a main method, the
class has two methods: `saveSettings()` saves the settings bean to a file named`settings.xml`, and `loadSettings()` loads these settings again. The following `main()` method
constructs a Spring application context and calls these two methods:

Java

```
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;

public class Application {

    private static final String FILE_NAME = "settings.xml";
    private Settings settings = new Settings();
    private Marshaller marshaller;
    private Unmarshaller unmarshaller;

    public void setMarshaller(Marshaller marshaller) {
        this.marshaller = marshaller;
    }

    public void setUnmarshaller(Unmarshaller unmarshaller) {
        this.unmarshaller = unmarshaller;
    }

    public void saveSettings() throws IOException {
        try (FileOutputStream os = new FileOutputStream(FILE_NAME)) {
            this.marshaller.marshal(settings, new StreamResult(os));
        }
    }

    public void loadSettings() throws IOException {
        try (FileInputStream is = new FileInputStream(FILE_NAME)) {
            this.settings = (Settings) this.unmarshaller.unmarshal(new StreamSource(is));
        }
    }

    public static void main(String[] args) throws IOException {
        ApplicationContext appContext =
                new ClassPathXmlApplicationContext("applicationContext.xml");
        Application application = (Application) appContext.getBean("application");
        application.saveSettings();
        application.loadSettings();
    }
}
```

Kotlin

```
class Application {

    lateinit var marshaller: Marshaller

    lateinit var unmarshaller: Unmarshaller

    fun saveSettings() {
        FileOutputStream(FILE_NAME).use { outputStream -> marshaller.marshal(settings, StreamResult(outputStream)) }
    }

    fun loadSettings() {
        FileInputStream(FILE_NAME).use { inputStream -> settings = unmarshaller.unmarshal(StreamSource(inputStream)) as Settings }
    }
}

private const val FILE_NAME = "settings.xml"

fun main(args: Array<String>) {
    val appContext = ClassPathXmlApplicationContext("applicationContext.xml")
    val application = appContext.getBean("application") as Application
    application.saveSettings()
    application.loadSettings()
}
```

The `Application` requires both a `marshaller` and an `unmarshaller` property to be set. We
can do so by using the following `applicationContext.xml`:

```
<beans>
    <bean id="application" class="Application">
        <property name="marshaller" ref="xstreamMarshaller" />
        <property name="unmarshaller" ref="xstreamMarshaller" />
    </bean>
    <bean id="xstreamMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller"/>
</beans>
```

This application context uses XStream, but we could have used any of the other marshaller
instances described later in this chapter. Note that, by default, XStream does not require
any further configuration, so the bean definition is rather simple. Also note that the`XStreamMarshaller` implements both `Marshaller` and `Unmarshaller`, so we can refer to the`xstreamMarshaller` bean in both the `marshaller` and `unmarshaller` property of the
application.

This sample application produces the following `settings.xml` file:

```
<?xml version="1.0" encoding="UTF-8"?>
<settings foo-enabled="false"/>
```

### [](#oxm-schema-based-config)6.4. XML Configuration Namespace ###

You can configure marshallers more concisely by using tags from the OXM namespace.
To make these tags available, you must first reference the appropriate schema in the
preamble of the XML configuration file. The following example shows how to do so:

```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:oxm="http://www.springframework.org/schema/oxm" (1)
xsi:schemaLocation="http://www.springframework.org/schema/beans
  https://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/oxm https://www.springframework.org/schema/oxm/spring-oxm.xsd"> (2)
```

|**1**|   Reference the `oxm` schema.    |
|-----|----------------------------------|
|**2**|Specify the `oxm` schema location.|

The schema makes the following elements available:

* [`jaxb2-marshaller`](#oxm-jaxb2-xsd)

* [`jibx-marshaller`](#oxm-jibx-xsd)

Each tag is explained in its respective marshaller’s section. As an example, though,
the configuration of a JAXB2 marshaller might resemble the following:

```
<oxm:jaxb2-marshaller id="marshaller" contextPath="org.springframework.ws.samples.airline.schema"/>
```

### [](#oxm-jaxb)6.5. JAXB ###

The JAXB binding compiler translates a W3C XML Schema into one or more Java classes, a`jaxb.properties` file, and possibly some resource files. JAXB also offers a way to
generate a schema from annotated Java classes.

Spring supports the JAXB 2.0 API as XML marshalling strategies, following the`Marshaller` and `Unmarshaller` interfaces described in [`Marshaller` and `Unmarshaller`](#oxm-marshaller-unmarshaller).
The corresponding integration classes reside in the `org.springframework.oxm.jaxb`package.

#### [](#oxm-jaxb2)6.5.1. Using `Jaxb2Marshaller` ####

The `Jaxb2Marshaller` class implements both of Spring’s `Marshaller` and `Unmarshaller`interfaces. It requires a context path to operate. You can set the context path by setting the`contextPath` property. The context path is a list of colon-separated Java package
names that contain schema derived classes. It also offers a `classesToBeBound` property,
which allows you to set an array of classes to be supported by the marshaller. Schema
validation is performed by specifying one or more schema resources to the bean, as the following example shows:

```
<beans>
    <bean id="jaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
        <property name="classesToBeBound">
            <list>
                <value>org.springframework.oxm.jaxb.Flight</value>
                <value>org.springframework.oxm.jaxb.Flights</value>
            </list>
        </property>
        <property name="schema" value="classpath:org/springframework/oxm/schema.xsd"/>
    </bean>

    ...

</beans>
```

##### [](#oxm-jaxb2-xsd)XML Configuration Namespace #####

The `jaxb2-marshaller` element configures a `org.springframework.oxm.jaxb.Jaxb2Marshaller`,
as the following example shows:

```
<oxm:jaxb2-marshaller id="marshaller" contextPath="org.springframework.ws.samples.airline.schema"/>
```

Alternatively, you can provide the list of classes to bind to the marshaller by using the`class-to-be-bound` child element:

```
<oxm:jaxb2-marshaller id="marshaller">
    <oxm:class-to-be-bound name="org.springframework.ws.samples.airline.schema.Airport"/>
    <oxm:class-to-be-bound name="org.springframework.ws.samples.airline.schema.Flight"/>
    ...
</oxm:jaxb2-marshaller>
```

The following table describes the available attributes:

|  Attribute  |      Description       |Required|
|-------------|------------------------|--------|
|    `id`     |The ID of the marshaller|   No   |
|`contextPath`| The JAXB Context path  |   No   |

### [](#oxm-jibx)6.6. JiBX ###

The JiBX framework offers a solution similar to that which Hibernate provides for ORM: A
binding definition defines the rules for how your Java objects are converted to or from
XML. After preparing the binding and compiling the classes, a JiBX binding compiler
enhances the class files and adds code to handle converting instances of the classes
from or to XML.

For more information on JiBX, see the [JiBX web
site](http://jibx.sourceforge.net/). The Spring integration classes reside in the `org.springframework.oxm.jibx`package.

#### [](#oxm-jibx-marshaller)6.6.1. Using `JibxMarshaller` ####

The `JibxMarshaller` class implements both the `Marshaller` and `Unmarshaller`interface. To operate, it requires the name of the class to marshal in, which you can
set using the `targetClass` property. Optionally, you can set the binding name by setting the`bindingName` property. In the following example, we bind the `Flights` class:

```
<beans>
    <bean id="jibxFlightsMarshaller" class="org.springframework.oxm.jibx.JibxMarshaller">
        <property name="targetClass">org.springframework.oxm.jibx.Flights</property>
    </bean>
    ...
</beans>
```

A `JibxMarshaller` is configured for a single class. If you want to marshal multiple
classes, you have to configure multiple `JibxMarshaller` instances with different `targetClass`property values.

##### [](#oxm-jibx-xsd)XML Configuration Namespace #####

The `jibx-marshaller` tag configures a `org.springframework.oxm.jibx.JibxMarshaller`,
as the following example shows:

```
<oxm:jibx-marshaller id="marshaller" target-class="org.springframework.ws.samples.airline.schema.Flight"/>
```

The following table describes the available attributes:

|  Attribute   |              Description               |Required|
|--------------|----------------------------------------|--------|
|     `id`     |        The ID of the marshaller        |   No   |
|`target-class`|  The target class for this marshaller  |  Yes   |
|`bindingName` |The binding name used by this marshaller|   No   |

### [](#oxm-xstream)6.7. XStream ###

XStream is a simple library to serialize objects to XML and back again. It does not
require any mapping and generates clean XML.

For more information on XStream, see the [XStream
web site](https://x-stream.github.io/). The Spring integration classes reside in the`org.springframework.oxm.xstream` package.

#### [](#oxm-xstream-marshaller)6.7.1. Using `XStreamMarshaller` ####

The `XStreamMarshaller` does not require any configuration and can be configured in an
application context directly. To further customize the XML, you can set an alias map,
which consists of string aliases mapped to classes, as the following example shows:

```
<beans>
    <bean id="xstreamMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller">
        <property name="aliases">
            <props>
                <prop key="Flight">org.springframework.oxm.xstream.Flight</prop>
            </props>
        </property>
    </bean>
    ...
</beans>
```

|   |By default, XStream lets arbitrary classes be unmarshalled, which can lead to<br/>unsafe Java serialization effects. As such, we do not recommend using the`XStreamMarshaller` to unmarshal XML from external sources (that is, the Web), as this can<br/>result in security vulnerabilities.<br/><br/>If you choose to use the `XStreamMarshaller` to unmarshal XML from an external source,<br/>set the `supportedClasses` property on the `XStreamMarshaller`, as the following example shows:<br/><br/>```<br/><bean id="xstreamMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller"><br/>    <property name="supportedClasses" value="org.springframework.oxm.xstream.Flight"/><br/>    ...<br/></bean><br/>```<br/><br/>Doing so ensures that only the registered classes are eligible for unmarshalling.<br/><br/>Additionally, you can register[custom<br/>converters](https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/oxm/xstream/XStreamMarshaller.html#setConverters(com.thoughtworks.xstream.converters.ConverterMatcher…​)) to make sure that only your supported classes can be unmarshalled. You might<br/>want to add a `CatchAllConverter` as the last converter in the list, in addition to<br/>converters that explicitly support the domain classes that should be supported. As a<br/>result, default XStream converters with lower priorities and possible security<br/>vulnerabilities do not get invoked.|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

|   |Note that XStream is an XML serialization library, not a data binding library.<br/>Therefore, it has limited namespace support. As a result, it is rather unsuitable for usage<br/>within Web Services.|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

[](#appendix)7. Appendix
----------

### [](#xsd-schemas)7.1. XML Schemas ###

This part of the appendix lists XML schemas for data access, including the following:

* [The `tx` Schema](#xsd-schemas-tx)

* [The `jdbc` Schema](#xsd-schemas-jdbc)

#### [](#xsd-schemas-tx)7.1.1. The `tx` Schema ####

The `tx` tags deal with configuring all of those beans in Spring’s comprehensive support
for transactions. These tags are covered in the chapter entitled[Transaction Management](#transaction).

|   |We strongly encourage you to look at the `'spring-tx.xsd'` file that ships with the<br/>Spring distribution. This file contains the XML Schema for Spring’s transaction<br/>configuration and covers all of the various elements in the `tx` namespace, including<br/>attribute defaults and similar information. This file is documented inline, and, thus,<br/>the information is not repeated here in the interests of adhering to the DRY (Don’t<br/>Repeat Yourself) principle.|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

In the interest of completeness, to use the elements in the `tx` schema, you need to have
the following preamble at the top of your Spring XML configuration file. The text in the
following snippet references the correct schema so that the tags in the `tx` namespace
are available to you:

```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" (1)
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx.xsd (2)
        http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!-- bean definitions here -->

</beans>
```

|**1**|       Declare usage of the `tx` namespace.        |
|-----|---------------------------------------------------|
|**2**|Specify the location (with other schema locations).|

|   |Often, when you use the elements in the `tx` namespace, you are also using the<br/>elements from the `aop` namespace (since the declarative transaction support in Spring is<br/>implemented by using AOP). The preceding XML snippet contains the relevant lines needed<br/>to reference the `aop` schema so that the elements in the `aop` namespace are available<br/>to you.|
|---|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

#### [](#xsd-schemas-jdbc)7.1.2. The `jdbc` Schema ####

The `jdbc` elements let you quickly configure an embedded database or initialize an
existing data source. These elements are documented in[Embedded Database Support](#jdbc-embedded-database-support) and[Initializing a DataSource](#jdbc-initializing-datasource), respectively.

To use the elements in the `jdbc` schema, you need to have the following preamble at the
top of your Spring XML configuration file. The text in the following snippet references
the correct schema so that the elements in the `jdbc` namespace are available to you:

```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc" (1)
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/jdbc https://www.springframework.org/schema/jdbc/spring-jdbc.xsd"> (2)

    <!-- bean definitions here -->

</beans>
```