この例では、Spring Boot Data JPAを使用して、MySQLデータベーステーブルにデータベーステーブルの挿入、更新、削除、および選択操作を実装する方法を説明します。スプリングブートデータJPAを使用すると、データベーステーブル操作コマンドがメソッドにラップされているため、基本的なスプリングブートデータJPAリポジトリインターフェイスを拡張するJavaインターフェイス( CrudRepository など)を作成する必要があります。 )、データベーステーブルの操作方法(findBy<列名>など)を定義するだけで済みます。 、 deleteBy <列名>、 など)カスタムリポジトリインターフェイスで、メソッド名は特別な命名規則に従う必要があります。リポジトリインターフェイスでSQLコマンドを記述する必要はありません。
1。 MySQLデータベーステーブルを作成します。
- dev2qa_exampleという名前のMySQLデータベースを作成します 。データベースのデフォルトの照合 utf8 – utf8_binである必要があります 。
CREATE SCHEMA `dev2qa_example` DEFAULT CHARACTER SET utf8 COLLATE utf8_bin ;
- テーブルを作成するuser_account 上記のdev2qa_example 以下のSQLステートメントを含むデータベース。 id 列はAIである必要があります (増分を自動化)、そうでない場合、エラーSpring Boot JPA Table'dbname.hibernate_sequence' Doesn'tExistがスローされます。
CREATE TABLE `dev2qa_example`.`user_account` ( `id` INT NOT NULL AUTO_INCREMENT, `user_name` VARCHAR(100) NULL, `password` VARCHAR(100) NULL, `email` VARCHAR(100) NULL, PRIMARY KEY (`id`)) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COLLATE = utf8_bin;
2。 SpringBootProjectを作成します。
- Spring Tool Suiteを起動し、[ファイル] —>[新規]—>[Springスタータープロジェクト]をクリックします 新しい春のスタータープロジェクトの下に開くメニュー項目 ウィザード。以下のように関連するプロジェクト情報を入力します。そして、[次へ]ボタンをクリックします。
- JPAを追加します 、 MySQL、 およびWeb 依存関係ウィザードのライブラリ。そして、完了をクリックします ボタンをクリックして、プロジェクトの初期化を完了します。
3。 Spring BootJPACRUDサンプルプロジェクトファイル。
以下は、このプロジェクトのソースファイルです。ひとつひとつご紹介します。
C:\WORKSPACE\WORK\DEV2QA.COM-EXAMPLE-CODE\SPRINGBOOT\SPRINGBOOTCRUDMYSQL
│ pom.xml
└───src
├───main
│ ├───java
│ │ └───com
│ │ └───dev2qa
│ │ └───example
│ │ │ SpringBootCrudMySqlApplication.java
│ │ │
│ │ ├───controller
│ │ │ UserAccountController.java
│ │ │
│ │ ├───entity
│ │ │ UserAccount.java
│ │ │
│ │ └───repository
│ │ UserAccountRepository.java
│ │
│ └───resources
│ application.properties
│
└───test
└───java
└───com
└───dev2qa
SpringBootCrudMySqlApplicationTests.java
3.1 SpringBootCrudMySqlApplication.java
これは、Javaクラスを開始するSpringBootの例です。スプリングブートアプリケーションで最初にロードされて実行されます。
package com.dev2qa.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
//@SpringBootApplication
@Configuration
@ComponentScan(basePackages = { "com.dev2qa.example" })
@EnableAutoConfiguration
public class SpringBootCrudMySqlApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootCrudMySqlApplication.class, args);
}
} 3.2 UserAccountController.java
これは、ユーザーリクエストのURLを処理メソッドにマップするSpringMVCコントローラーのJavaクラスです。
package com.dev2qa.example.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.dev2qa.example.entity.UserAccount;
import com.dev2qa.example.repository.UserAccountRepository;
@Controller
@RequestMapping(path = "/userAccount")
public class UserAccountController {
@Autowired
UserAccountRepository userAccountRepository;
/*
* Mapping url exmaple:
* https://localhost:8080/userAccount/add?userName=Jerry&password=888888&email=
* jexample@sqldat.com
* https://localhost:8080/userAccount/add?userName=Richard&password=888888&email=
* example@sqldat.com
*/
@GetMapping(path = "/add")
@ResponseBody
public String addUser(@RequestParam String userName, @RequestParam String password, @RequestParam String email) {
UserAccount userAccount = new UserAccount();
userAccount.setUsername(userName);
userAccount.setPassword(password);
userAccount.setEmail(email);
userAccountRepository.save(userAccount);
String ret = "User account has been added, user name = " + userName + ", password = " + password + ", email = "
+ email;
return ret;
}
/*
* Mapping url exmaple: https://localhost:8080/userAccount/findAll
*/
@GetMapping(path = "/findAll")
@ResponseBody
public String findAllUser() {
StringBuffer retBuf = new StringBuffer();
List<UserAccount> userAccountList = (List<UserAccount>) userAccountRepository.findAll();
if (userAccountList != null) {
for (UserAccount userAccount : userAccountList) {
retBuf.append("user name = ");
retBuf.append(userAccount.getUsername());
retBuf.append(", password = ");
retBuf.append(userAccount.getPassword());
retBuf.append(", email = ");
retBuf.append(userAccount.getEmail());
retBuf.append("\r\n");
}
}
if (retBuf.length() == 0) {
retBuf.append("No record find.");
} else {
retBuf.insert(0, "<pre>");
retBuf.append("</pre>");
}
return retBuf.toString();
}
/*
* Mapping url exmaple:
* https://localhost:8080/userAccount/findByName?userName=Jerry
*/
@GetMapping(path = "/findByName")
@ResponseBody
public String findByName(@RequestParam String userName) {
StringBuffer retBuf = new StringBuffer();
List<UserAccount> userAccountList = (List<UserAccount>) userAccountRepository.findByUsername(userName);
if (userAccountList != null) {
for (UserAccount userAccount : userAccountList) {
retBuf.append("user name = ");
retBuf.append(userAccount.getUsername());
retBuf.append(", password = ");
retBuf.append(userAccount.getPassword());
retBuf.append(", email = ");
retBuf.append(userAccount.getEmail());
retBuf.append("\r\n");
}
}
if (retBuf.length() == 0) {
retBuf.append("No record find.");
}
return retBuf.toString();
}
/*
* Mapping url exmaple:
* https://localhost:8080/userAccount/findByNameAndPassword?userName=Jerry&
* password=888888
*/
@GetMapping(path = "/findByNameAndPassword")
@ResponseBody
public String findByNameAndPassword(@RequestParam String userName, @RequestParam String password) {
StringBuffer retBuf = new StringBuffer();
List<UserAccount> userAccountList = (List<UserAccount>) userAccountRepository
.findByUsernameAndPassword(userName, password);
if (userAccountList != null) {
for (UserAccount userAccount : userAccountList) {
retBuf.append("user name = ");
retBuf.append(userAccount.getUsername());
retBuf.append(", password = ");
retBuf.append(userAccount.getPassword());
retBuf.append(", email = ");
retBuf.append(userAccount.getEmail());
retBuf.append("<br/>");
}
}
if (retBuf.length() == 0) {
retBuf.append("No record find.");
}
return retBuf.toString();
}
/*
* Mapping url exmaple:
* https://localhost:8080/userAccount/updateUser?userName=Jerry&password=hello&
* example@sqldat.com
*/
@GetMapping(path = "/updateUser")
@ResponseBody
public String updateUser(@RequestParam String userName, @RequestParam String password, @RequestParam String email) {
StringBuffer retBuf = new StringBuffer();
List<UserAccount> userAccountList = userAccountRepository.findByUsername(userName);
if (userAccountList != null) {
for (UserAccount userAccount : userAccountList) {
userAccount.setUsername(userName);
userAccount.setPassword(password);
userAccount.setEmail(email);
userAccountRepository.save(userAccount);
}
}
retBuf.append("User data update successfully.");
return retBuf.toString();
}
/*
* Mapping url exmaple:
* https://localhost:8080/userAccount/deleteByUserName?userName=Richard
*/
@GetMapping(path = "/deleteByUserName")
@ResponseBody
public String deleteByUserName(@RequestParam String userName) {
StringBuffer retBuf = new StringBuffer();
userAccountRepository.deleteByUsername(userName);
retBuf.append("User data has been deleted successfully.");
return retBuf.toString();
}
/*
* Mapping url exmaple:
* https://localhost:8080/userAccount/deleteByUserNameAndPassword?userName=
* Richard&password=888888
*/
@GetMapping(path = "/deleteByUserNameAndPassword")
@ResponseBody
public String deleteByUserNameAndPassword(@RequestParam String userName, @RequestParam String password) {
StringBuffer retBuf = new StringBuffer();
userAccountRepository.deleteByUsernameAndPassword(userName, password);
retBuf.append("User data has been deleted successfully.");
return retBuf.toString();
}
}"); } return retBuf.toString(); } / * *マッピングURLの例:* http:// localhost:8080 / userAccount / findByName?userName =Jerry * / @GetMapping(path ="/ findByName")@ResponseBody public String findByName(@RequestParam String userName){StringBuffer retBuf =new StringBuffer(); List "); }} if(retBuf.length()==0){retBuf.append( "レコードが見つかりません。"); } return retBuf.toString(); } / * *マッピングURLの例:* http:// localhost:8080 / userAccount / updateUser?userName =Jerry&password =hello&* example@sqldat.com * / @GetMapping(path ="/ updateUser")@ResponseBody public String updateUser( @RequestParam String userName、@ RequestParam String password、@ RequestParam String email){StringBuffer retBuf =new StringBuffer(); List
3.3 UserAccount.java
これは、MySQLテーブル user_accountにマップされるエンティティJavaクラスです。 。 idに注意してください 生成戦略はGenerationType.IDENTITYである必要があります 、 Generation.AUTOを使用する場合 MySQLテーブルID列が自動インクリメントに設定されている場合、エラーがスローされます。
package com.dev2qa.example.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/* Map this entity class to user_account table. */
@Entity(name = "user_account")
public class UserAccount {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@javax.persistence.Column(name = "user_name")
private String username;
private String password;
private String email;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
} 3.4 UserAccountRepository.java
これは、 CrudRepositoryを拡張するカスタムスプリングブートデータJPAリポジトリインターフェースです。 。関連するメソッドを定義するだけで、SpringFrameworkは関連するSQLコマンドを自動的に実行してメソッドを実装します。これにより、コーディングがより迅速になります。
package com.dev2qa.example.repository;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import org.springframework.transaction.annotation.Transactional;
import com.dev2qa.example.entity.UserAccount;
public interface UserAccountRepository extends CrudRepository<UserAccount, Long> {
/*
* Get user list by user name. Please note the format should be
* findBy<column_name>.
*/
List<UserAccount> findByUsername(String username);
/*
* Get user list by user name and password. Please note the format should be
* findBy<column_name_1>And<column_name_2>.
*/
List<UserAccount> findByUsernameAndPassword(String username, String password);
@Transactional
void deleteByUsernameAndPassword(String username, String password);
@Transactional
void deleteByUsername(String username);
} 3.5 application.properties
これは、例で使用されているMySQLJDBCデータソース接続データを含むリソースファイルです。
# MySQL jdbc connection url. spring.datasource.url=jdbc:mysql://localhost:3306/dev2qa_example # MySQL jdbc driver class name. spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver # MySQL database username and password spring.datasource.username=root spring.datasource.password=root
3.6 pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>SpringBootCRUDMySQL</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SpringBootCRUDMySQL</name>
<description>Spring boot access mysql with crud operation.</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project> 3.7例を実行します。
- プロジェクト名を右クリックします。
- 実行—> Spring Boot Appをクリックします ポップアップメニューリストのメニュー項目。
- アプリケーションの起動後、関連する UserAccountControllerのマッピングURLを入力します 結果を確認するには、WebブラウザのJavaクラスメソッドを使用します。
4。質疑応答。
4.1 SpringブートメソッドfindAll、findById、deleteByIdはすべて空の結果を返します。
- Spring boot + MySQLを使用して、MySQLテーブルを操作するためのCRUDアクションを実行するRESTアプリケーションを実装したいと思います。しかし、 findAll()を実行すると見つかります メソッド、それは空のリストを返します、これは私が期待するものではありません。 findById()を実行すると メソッドの場合、エラーメッセージ java.util.NoSuchElementException:No value present 。そして、スプリングブートメソッド deleteById()で削除アクションを実行すると 、ID10のクラスorg.dev2qa.entity.Articleエンティティが存在しないこともわかります。 !私のデータベーステーブルは空のようですが、そうではありません。どのような場合にこれらのエラーが発生する可能性がありますか?
- 私のカスタムリポジトリクラスはJpaRepositoryを拡張します クラス、およびその findAll() メソッドも空のリストを返します。私のデータベースはMySqlデータベースでもあります。 MySQLデータベースに1つのレコードを追加すると、 findAll() メソッドは[{}]を返します 、およびMySQLデータベースに2つのレコードを追加すると、 findAll() メソッドは[{}、{}]を返します 。リストの要素番号は正しいですが、要素データが空です。これは正しくありません。誰か助けてもらえますか?どうもありがとう。
- エンティティクラスのプロパティが公開されていない場合、このエラーが発生する可能性があります。まず、 @Columnを使用してエンティティクラスのプロパティを宣言する必要があります アノテーションとプロパティ宣言はプライベートにすることができ、次にそれらのプロパティにgettersとsettersメソッドを追加し、gettersとsettersメソッドをパブリックにします。この後、JpaRepositoryはエンティティオブジェクトを作成し、MySQLデータベースから読み戻されたデータをオブジェクトのプロパティに入力できます。そして、あなたの findAll() メソッドは空のリストをまったく返しません。
参照
- UbuntuにMySQLをインストールする方法
- SpringBootJPAテーブル「dbname.hibernate_sequence」が存在しないというエラーを解決する