Spring Boot および MyBatis の構成実践ガイド
はじめに:
Spring Boot は、Spring アプリケーションの起動およびデプロイメント プロセスを簡素化するために使用される高速開発フレームワークです。 MyBatis は、さまざまなリレーショナル データベースと簡単に対話できる人気のある永続化フレームワークです。この記事では、Spring Boot プロジェクトで MyBatis を構成して使用する方法を紹介し、具体的なコード例を示します。
1. プロジェクト構成
1. 依存関係の導入
pom.xml ファイルに、次の依存関係を追加します:
<dependencies> <!-- Spring Boot Web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- MyBatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> </dependency> <!-- 数据库驱动(例如,MySQL)--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependencies>
2. データベース接続の構成
Inapplication.properties
ファイルで、データベース接続情報を構成します。たとえば、MySQL データベースを使用する場合、次の構成を追加できます:
spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver
2. エンティティ クラス
1 を作成します。
com.example 内にエンティティ クラス を作成します。 .demo.entity
パッケージで、User
:
public class User { private int id; private String name; private String email; // 省略 getters 和 setters }
2 という名前のエンティティ クラスを作成します。
com.example.demo.mapper# 内にマッパー インターフェイスを作成します## パッケージ、作成 UserMapper
という名前のインターフェイス: <pre class='brush:php;toolbar:false;'>public interface UserMapper {
List<User> getAllUsers();
User getUserById(int id);
void addUser(User user);
void updateUser(User user);
void deleteUser(int id);
}</pre>
3. マッパー XML ファイルの作成
UserMapper
を作成します UserMapper.xml
、対応する SQL 操作を構成します: <pre class='brush:php;toolbar:false;'><?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.example.demo.entity.User">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="email" property="email"/>
</resultMap>
<select id="getAllUsers" resultMap="BaseResultMap">
SELECT * FROM user
</select>
<select id="getUserById" resultMap="BaseResultMap">
SELECT * FROM user WHERE id=#{id}
</select>
<insert id="addUser">
INSERT INTO user(name, email) VALUES (#{name}, #{email})
</insert>
<update id="updateUser">
UPDATE user SET name=#{name}, email=#{email} WHERE id=#{id}
</update>
<delete id="deleteUser">
DELETE FROM user WHERE id=#{id}
</delete>
</mapper></pre>
4. MyBatis を構成します
com.example.demo.config
パッケージ内MyBatisConfig
: <pre class='brush:php;toolbar:false;'>@Configuration
@MapperScan("com.example.demo.mapper")
public class MyBatisConfig {
}</pre>
2 という名前の構成クラスを作成します。構成を完了します
application.properties
ファイルに、次の構成を追加します: <pre class='brush:php;toolbar:false;'># MyBatis
mybatis.mapper-locations=classpath*:com/example/demo/mapper/*.xml</pre>
ここまでで、プロジェクトの構成と準備が完了しました。次に、Spring Boot プロジェクトで MyBatis を使用する方法を学びます。
5. MyBatis の使用
1. ビジネス ロジックの作成
com.example.demo.service
パッケージで、UserService
クラスという名前のサービスを作成します: <pre class='brush:php;toolbar:false;'>@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public List<User> getAllUsers() {
return userMapper.getAllUsers();
}
public User getUserById(int id) {
return userMapper.getUserById(id);
}
public void addUser(User user) {
userMapper.addUser(user);
}
public void updateUser(User user) {
userMapper.updateUser(user);
}
public void deleteUser(int id) {
userMapper.deleteUser(id);
}
}</pre>
2. コントローラーの作成
com.example.demo.controller
パッケージで、UserController
:<pre class='brush:php;toolbar:false;'>@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("")
public List<User> getAllUsers() {
return userService.getAllUsers();
}
@GetMapping("/{id}")
public User getUserById(@PathVariable int id) {
return userService.getUserById(id);
}
@PostMapping("")
public void addUser(@RequestBody User user) {
userService.addUser(user);
}
@PutMapping("/{id}")
public void updateUser(@PathVariable int id, @RequestBody User user) {
user.setId(id);
userService.updateUser(user);
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable int id) {
userService.deleteUser(id);
}
}</pre> という名前のコントローラー クラスを作成します。
3. API のテスト
- 単一ユーザーの取得: http://localhost:8080/users/{id}
- ユーザーの追加: POST http://localhost:8080/users、リクエスト本文は次のとおりです。 JSON 形式のユーザー オブジェクト
- ユーザーの更新: PUT http://localhost:8080/users/{id}、リクエスト本文は JSON 形式のユーザー オブジェクトです
- ユーザーの削除: DELETE http: //localhost :8080/users/{id}
- 概要:
以上がSpring Boot および MyBatis 構成のヒント ガイドの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

jvm'sperformanceiscompetitivewitherruntimes、sped、safety、andproductivityの提供

javaachievesplatformedentenceTheThejavavirtualMachine(JVM)、avainwithcodetorunonanyplatformwithajvm.1)codescompiledintobytecode、notmachine-specificcode.2)

thejvmisanabstractcomputingMachineCrucialForrunningJavaProgramsDuetoitsPlatForm-IndopentInterChitecture.Itincludes:1)ClassLoaderForloadingClasses、2)Runtimedataareaforforforatastorage、3)executionEngineWithinterter、Jitcompiler、およびGarbagecolfecolfecolfececolfecolfer

jvmhasacloserelationshiptheosasittrantesjavabytecodecodecodecodecodecodecodecodecodecodecodecodecodetructions、manageSmemory、およびhandlesgarbagecollection.thisrelationshipallowsjavatorunonvariousosenvirnments、Butalsedentsはspeedifediferentjvmbeviorhiorsandosendisfredediferentjvmbehbehioorysando

Javaの実装「Write and、Run Everywherewhere」はBytecodeにコンパイルされ、Java仮想マシン(JVM)で実行されます。 1)Javaコードを書き、それをByteCodeにコンパイルします。 2)JVMがインストールされたプラットフォームでByteCodeが実行されます。 3)Javaネイティブインターフェイス(JNI)を使用して、プラットフォーム固有の機能を処理します。 JVMの一貫性やプラットフォーム固有のライブラリの使用などの課題にもかかわらず、Woraは開発効率と展開の柔軟性を大幅に向上させます。

javaachievesplatformentenceTheTheTheJavavirtualMachine(JVM)、CodetorunondifferentoperatingSystemswithOutModification.thejvmcompilesjavacodeplatform-IndopentedbyTecodeを承認することを許可します

javaispowerfulfulduetoitsplatformindepentence、object-orientednature、richstandardlibrary、performancecapability、andstrongsecurityfeatures.1)platformendependenceallowseplicationStorunonaydevicesupportingjava.2)オブジェクト指向のプログラマン型

上位のJava関数には、次のものが含まれます。1)オブジェクト指向プログラミング、サポートポリ型、コードの柔軟性と保守性の向上。 2)例外処理メカニズム、トライキャッチ式ブロックによるコードの堅牢性の向上。 3)ゴミ収集、メモリ管理の簡素化。 4)ジェネリック、タイプの安全性の向上。 5)コードをより簡潔で表現力豊かにするためのAMBDAの表現と機能的なプログラミング。 6)最適化されたデータ構造とアルゴリズムを提供するリッチ標準ライブラリ。


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

SublimeText3 英語版
推奨: Win バージョン、コードプロンプトをサポート!

SecLists
SecLists は、セキュリティ テスターの究極の相棒です。これは、セキュリティ評価中に頻繁に使用されるさまざまな種類のリストを 1 か所にまとめたものです。 SecLists は、セキュリティ テスターが必要とする可能性のあるすべてのリストを便利に提供することで、セキュリティ テストをより効率的かつ生産的にするのに役立ちます。リストの種類には、ユーザー名、パスワード、URL、ファジング ペイロード、機密データ パターン、Web シェルなどが含まれます。テスターはこのリポジトリを新しいテスト マシンにプルするだけで、必要なあらゆる種類のリストにアクセスできるようになります。

Safe Exam Browser
Safe Exam Browser は、オンライン試験を安全に受験するための安全なブラウザ環境です。このソフトウェアは、あらゆるコンピュータを安全なワークステーションに変えます。あらゆるユーティリティへのアクセスを制御し、学生が無許可のリソースを使用するのを防ぎます。

AtomエディタMac版ダウンロード
最も人気のあるオープンソースエディター

メモ帳++7.3.1
使いやすく無料のコードエディター
