SpringのSQLストアドプロシージャ
アプローチを理解するために、次のDDLを使用してMySQL TESTデータベースに作成できるStudentテーブルを取り上げます-
次に、次のMySQLストアドプロシージャについて考えます。これは、学生IDを取得し、OUTパラメータを使用して対応する学生の名前と年齢を返します。 MySQLコマンドプロンプトを使用してTESTデータベースにこのストアドプロシージャを作成しましょう-
次に、Studentテーブルに簡単なCreateおよびRead操作を実装するSpring JDBCアプリケーションを作成しましょう。 動作するEclipse IDEを用意し、次の手順を実行してSpringアプリケーションを作成します。
Steps | Description |
---|---|
1 | Create a project with a name SpringExample and create a package com.finddevguides under the *src *folder in the created project. |
2 | Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter. |
3 | Add Spring JDBC specific latest libraries* mysql-connector-java.jar*, org.springframework.jdbc.jar *and org.springframework.transaction.jar *in the project. You can download required libraries if you do not have them already. |
4 | Create DAO interface StudentDAO and list down all the required methods. Though it is not required and you can directly write StudentJDBCTemplate class, but as a good practice, let’s do it. |
5 | Create other required Java classes Student, StudentMapper, StudentJDBCTemplate and MainApp under the com.finddevguides package. |
6 | Make sure you already created* Student *table in TEST database. Also make sure your MySQL server is working fine and you have read/write access on the database using the given username and password. |
7 | Create Beans configuration file Beans.xml under the* src* folder. |
8 | The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below. |
以下は、データアクセスオブジェクトインターフェイスファイル StudentDAO.java の内容です。
以下は Student.java ファイルの内容です
以下は StudentMapper.java ファイルの内容です
以下は、定義済みのDAOインターフェイスStudentDAOの実装クラスファイル StudentJDBCTemplate.java です-
上記のプログラムに関するいくつかの言葉:呼び出しの実行のために記述するコードには、INパラメーターを含む_SqlParameterSource_の作成が含まれます。 入力値に指定された名前を、ストアドプロシージャで宣言されたパラメーター名と一致させることが重要です。 _execute_メソッドは、INパラメータを受け取り、ストアドプロシージャで指定された名前をキーとする出力パラメータを含むマップを返します。 次に、メインアプリケーションファイル MainApp.java を使用します。これは次のとおりです-
以下は設定ファイル Beans.xml です
ソースおよびBean構成ファイルの作成が完了したら、アプリケーションを実行しましょう。 すべてがあなたのアプリケーションでうまくいけば、それは次のメッセージを印刷します-