Spring-jdbc-example
提供:Dev Guides
Spring JDBCの例
JdbcTemplateクラスを使用したSpring JDBCフレームワークに関連する概念を理解するために、次のStudentテーブルですべてのCRUD操作を実装する簡単な例を作成しましょう。
先に進む前に、機能する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 give 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 を次に示します。
以下は MainApp.java ファイルの内容です
以下は設定ファイル Beans.xml です
ソースおよびBean構成ファイルの作成が完了したら、アプリケーションを実行しましょう。 すべてがあなたのアプリケーションでうまくいけば、それは次のメッセージを印刷します-
この例では使用していない操作を自分で試して削除できますが、Spring JDBCフレームワークに基づいた1つの作業アプリケーションがあり、プロジェクト要件に基づいて高度な機能を追加することができます。 NamedParameterJdbcTemplate クラスと SimpleJdbcTemplate クラスを使用するデータベースにアクセスする他の方法があるため、これらのクラスの学習に興味がある場合は、Spring Frameworkのリファレンスマニュアルをご確認ください。