目次
1: ORM が MySQL を操作する
MyBatis フレームワークを使用してデータを操作し、MyBatis を SpringBoot フレームワークに統合し、次の手順を実行します。
(1) mybatis 起動依存関係: mybatis オブジェクトの自動構成を完了し、オブジェクトをコンテナーに配置します。
(2) pom.xml は、src/main/java ディレクトリ内の xml ファイルをクラスパスに含めるように指定します。
(3) エンティティクラス Student を作成する
(4) DaoインターフェースStudentDaoを作成し、学生にクエリを実行するメソッドを作成します
(5) Daoインターフェースに対応したMapperファイル、xmlファイルを作成し、SQL文を記述する
(6) Service層オブジェクトを作成し、StudentServiceインターフェースとその実装クラスを作成します。daoオブジェクトを削除してデータベースの操作を完了する方法
(7) Controller オブジェクトを作成し、Service にアクセスします。
(8) application.propertiesファイルを記述し、データベースの接続情報を設定します。
1. Spring Boot プロジェクトを作成する
(1) データベーステーブルの準備
フィールドとそのタイプ
データを挿入する
(2) SpringBootプロジェクトの作成
Spring Web依存関係を選択します
MybatisFramework 依存関係、MySQL Driver 依存関係
(3) 生成されたpom.xml設定と手動で追加されたリソースプラグイン設定
注: リソース プラグイン構成は、src/java/main またはサブパッケージの下にある *.xml 構成ファイルが最終的に target/classes ディレクトリにロードされることを意味します。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.9</version>
<relativePath/>
</parent>
<groupId>com.zl</groupId>
<artifactId>study-springboot-mysql</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--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>
<version>2.3.0</version>
</dependency>
<!--mysql驱动依赖-->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<!--测试-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<!--手动添加resources插件-->
<resources>
<resource>
<!--指定目录-->
<directory>src/main/java</directory>
<!--指定目录下的文件-->
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
<!--plugins插件-->
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
(4) エンティティクラス
データベースのフィールド名と属性名が一致するエンティティクラスを用意します。
package com.zl.pojo;
public class Student {
private Integer id;
private String name;
private Integer age;
public Student() {
}
public Student(Integer id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
(5) Daoインターフェースの作成
@Mapper アノテーションをクラスに追加する必要があります。これが dao インターフェイスであることを MyBatis に伝え、このインターフェイスのプロキシ オブジェクトを作成します。
package com.zl.dao;
import com.zl.pojo.Student;
import org.apache.ibatis.annotations.Mapper;
@Mapper //用来创建代理对象的
public interface StudentDao {
// 根据id进行查询
Student selectById(@Param("stuId") Integer id);
}
(6) Daoインターフェース下に同じ名前のStudentDao.xmlファイルを作成します。
注: 前に構成したリソース構成は、この StudentDao.xml 構成サービス用です。
<?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.zl.dao.StudentDao">
<!--编写sql语句,id是这条sql语句的唯一表示-->
<select id="selectById" resultType="com.zl.pojo.Student">
select id,name,age from t_student where id = #{stuId}
</select>
</mapper>
(7) Serviceインターフェースと対応する実装クラスを記述する
StudentService インターフェース
package com.zl.service;
import com.zl.pojo.Student;
public interface StudentService {
// 方法调用
Student queryStudent(Integer id);
}
StudentService インターフェイス実装クラス、ビジネス ロジックを作成する
package com.zl.service.impl;
import com.zl.dao.StudentDao;
import com.zl.pojo.Student;
import com.zl.service.StudentService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service // 交给Spring容器管理
public class StudentServiceImpl implements StudentService {
// 调用Dao
@Resource // 给属性赋值
private StudentDao studentDao;
@Override
public Student queryStudent(Integer id) {
Student student = studentDao.selectById(id);
return student;
}
}
(8) サービスを呼び出すコントローラーを作成する
package com.zl.controller;
import com.zl.pojo.Student;
import com.zl.service.StudentService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
@Controller
public class StudentController {
@Resource
public StudentService studentService;
@RequestMapping("/student/query")
@ResponseBody
public String queryStudent(Integer id){
Student student = studentService.queryStudent(id);
return student.toString();
}
}
(9) データベースに接続するには、application.properties の設定が必要です
useUnicode は Unicode エンコーディングを使用し、characterEncoding 文字セットは utf-8、serverTimezone タイム ゾーンです。
server.port=9090
server.servlet.context-path=/orm
#连接数据库的配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123
(10) 実行結果
2. @MapperScan
Daoインターフェースが複数ある場合、それぞれのDaoインターフェースに@Mapperアノテーションを付ける必要があり面倒です。
StudentDao インターフェース
package com.zl.dao;
import com.zl.pojo.Student;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface StudentDao {
// 根据id进行查询
Student selectById(Integer id);
}
UserDao インターフェース
package com.zl.dao;
import com.zl.pojo.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserDao {
// 根据id进行查询
SUser selectById(Integer id);
}
注釈パッケージ スキャン @MapperScan("com.zl.dao") をメイン クラス (スタートアップ クラス上) に追加することもできます。
注:basePackages は String 配列であり、スキャンする複数のパッケージを記述することができます。
package com.zl;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan(basePackages = "com.zl.dao")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
詳細:
プロジェクトをインポートすると、IDEA はリソースを認識できず、アイコンは次のようになります。
マウスを右クリックします ----「ディレクトリを次のようにマークする-----」 リソース ルート
この時のアイコンは以下の通りです。
3. マッパーファイルとJavaコードは別々に管理されます
現在の XML ファイルと Java コードは同じパッケージで管理されています。
個別に保存することもでき、xml ファイルをリソース ディレクトリに置きます。リソースの下にマッパー ディレクトリを作成し、すべての *.xml をその中に置きますが、この時点では見つからないため、設定して指定する必要があります。
このとき、application.properties ファイルで次のように指定する必要があります。
#指定mapper文件的位置
mybatis.mapper-locations=classpath:mapper/*.xml
注: 現時点では、Springboot の下位バージョンでは、application.properties ファイルが target/classes ディレクトリにコンパイルされていない可能性があるため、リソース プラグインの構成を変更する必要があります。
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
SQL文の情報を確認するには、application.propertiesにログフレームワークを追加する必要があります。
#指定mybatis的日志,使用StdOutImpl输出到控制台
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
この時点で、SQL ステートメントのログ情報が表示されます。
4. トランザクションサポート
Spring フレームワークのトランザクション:
(1) トランザクションを管理するオブジェクトを使用する: トランザクション マネージャー (インターフェイス、インターフェイスには多くの実装クラスがあります)
例: Jdbc または mybatis を使用してデータベースにアクセスし、使用されるトランザクション マネージャー: DataSourceTransactionManager
(2) 宣言型トランザクション:トランザクション制御の内容をxml設定ファイルに記述する、またはアノテーションを使用する
トランザクションの制御: 分離レベル、伝播動作、タイムアウトなど。
(3) トランザクション処理方法:
① Spring フレームワークの @Transactional。
②aspectjフレームワークはトランザクション制御の内容をxml設定ファイルで宣言できます。
SpringBoot でトランザクションを使用するのは非常に簡単で、最下層では引き続き Spring 自体が提供するトランザクション管理を使用します。
①ビジネスメソッドの上に@Transactionalを追加し、アノテーションを追加したメソッドにトランザクション機能を持たせます。
②メイン起動クラスの上に @EnableTransactionManager を追加してトランザクションサポートを有効にします。
注: @Transactional を追加するだけでもトランザクション機能を完了できます。@EnableTransactionManager を追加することも推奨されます。
ステップ 1: SpringBoot プロジェクトを作成し、Spring Web、MybatisFramework、MySQL Driver を導入します。
ステップ 2: mybatis リバース エンジニアリング プラグインを使用して、pojo クラスと dao インターフェイスを生成する
①Mybatisリバースエンジニアリングプラグインを追加
注:このプラグインには MySQL ドライバーの依存関係が必要です。ここで紹介されている MySQL ドライバーの依存関係がない場合は、データベースに接続する JDBC ドライバー パッケージの場所を指定するために、以下のgeneratorConfig.xml 構成に <classPathEntry> タグが必要です。フルパス (例: <classPathEntry location="E:\mysql-connector-java-5.1.38.jar"/>)。
<!--mybatis逆向⼯程插件-->
<plugin>
<!--插件的GAV坐标-->
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.4.1</version>
<configuration>
<!--配置文件的位置,放在项目根目录下必须指定一下-->
<!--<configurationFile>GeneratorMapper.xml</configurationFile>-->
<!--允许覆盖-->
<overwrite>true</overwrite>
</configuration>
<!--插件的依赖-->
<dependencies>
<!--mysql驱动依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.23</version>
</dependency>
</dependencies>
</plugin>
② 設定ファイルgeneratorConfig.xmlを書き込む
注:次のgeneratorConfig.xml設定ファイルがsrcのresourcesディレクトリに配置されている場合、設定ファイルの名前はgeneratorConfig.xml(大文字と小文字は区別されません)である必要があり、上記の<configurationFile>タグを指定する必要はありません。
注: generatorConfig.xml 構成ファイルをプロジェクトのルート ディレクトリ (src と同じレベルのディレクトリ) に直接配置する場合、現時点では、generatorConfig.xml 構成ファイルの名前は任意ですが、上記の < を使用する必要があります。 configurationFile> タグで指定します (両方を一貫させることができます)。
注:もちろん、これをプロジェクトのルート ディレクトリに直接置くことはできません。たとえば、これを src/main ディレクトリに置く場合は、<configurationFile> タグに src/main/generatorConfig.xml を指定する必要があります (両方が一貫している必要があります)
注: MySQL ドライバーの上位バージョンでは、タイム ゾーンは URL に従う必要がありますが、xml では & が認識されないため、次のように & を使用して置き換える必要があります。
connectionURL="jdbc:mysql://localhost:3306/springdb?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8"
最後に、*.xml 構成が生成されます。これをコンパイルしてターゲット/クラスに配置する場合は、処理リソースのディレクトリを構成する必要があります
<!--处理资源目录-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
</resource>
</resources>
generatorConfig.xml 構成
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- 指定连接数据库的JDBC驱动包所在位置,如果前面插件中指定了,这里就不要指定了 -->
<!--<classPathEntry location="E:\mysql-connector-java-5.1.38.jar"/>-->
<!--
targetRuntime有两个值:
MyBatis3Simple:生成的是基础版,只有基本的增删改查。
MyBatis3:生成的是增强版,除了基本的增删改查之外还有复杂的增删改查。
-->
<context id="DB2Tables" targetRuntime="MyBatis3Simple">
<!--防止生成重复代码-->
<plugin type="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin"/>
<commentGenerator>
<!--是否去掉生成日期-->
<property name="suppressDate" value="true"/>
<!--是否去除注释-->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--连接数据库信息-->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/springboot"
userId="root"
password="123">
</jdbcConnection>
<!-- 生成pojo包名和位置 -->
<javaModelGenerator targetPackage="com.zl.pojo" targetProject="src/main/java">
<!--是否开启子包-->
<property name="enableSubPackages" value="true"/>
<!--是否去除字段名的前后空白-->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成SQL映射文件的包名和位置 -->
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
<!--是否开启子包-->
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 生成Mapper接口的包名和位置 -->
<javaClientGenerator
type="xmlMapper"
targetPackage="com.zl.mapper"
targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 表名和对应的实体类名-->
<table tableName="t_Student" domainObjectName="Student"/>
</context>
</generatorConfiguration>
プラグインをダブルクリックすると、実行結果は次のようになります。
ステップ 3: application.properties 構成を作成する
注: StudentMapper.xml ディレクトリが StudentMapper ディレクトリと一致する場合、次の構成 mybatis.mapper-locations=classpath:mapper/*.xml は必要ありません。ここではマッパー ディレクトリを定義し、その中に Mapper.xml ファイルを置きます。 , そのため、その場所を指定する必要があります。
#设置端口
server.port=8082
#配置项目根路径context-path
server.servlet.context-path=/myboot
#配置数据库
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123
#配置mybatis
mybatis.mapper-locations=classpath:mapper/*.xml
#配置日志
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
ステップ 4: サービス インターフェイスと実装クラスを作成する
StudentService インターフェース
package com.zl.service;
import com.zl.pojo.Student;
public interface StudentService {
int addStudent(Student student);
}
StudentService インターフェースの実装クラス StudentServiceImpl
package com.zl.service.impl;
import com.zl.mapper.StudentMapper;
import com.zl.pojo.Student;
import com.zl.service.StudentService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
@Service // 交给Spring容器管理
public class StudentServiceImpl implements StudentService {
@Resource // 属性赋值
private StudentMapper studentDao;
@Transactional // 事务控制
@Override
public int addStudent(Student student) {
System.out.println("准备执行sql语句");
int count = studentDao.insert(student);
System.out.println("已完成sql语句的执行");
// 模拟异常,回滚事务
int sum = 10 / 0;
return count;
}
}
ステップ 5: サービスを呼び出すコントローラー クラスを作成する
package com.zl.controller;
import com.zl.pojo.Student;
import com.zl.service.StudentService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
@Controller
public class StudentController {
@Resource
private StudentService studentService;
@RequestMapping("/addStudent")
@ResponseBody
public String addStudent(String name,Integer age){
Student s = new Student();
s.setName(name);
s.setAge(age);
int count = studentService.addStudent(s);
return "添加的Student个数是:"+count;
}
}
ステップ 6: パッケージ スキャン アノテーションとスタートアップ トランザクション マネージャー アノテーションをスタートアップ クラスに追加する
package com.zl;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@SpringBootApplication
@MapperScan(basePackages = "com.zl.mapper") // 添加包扫描
@EnableTransactionManagement // 启动事务管理器
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
ステップ 7: テストを実行する
例外が発生し、トランザクションはロールバックされ、データを挿入できません
異常は発生せず、正常にデータを挿入します