検索
ホームページphp教程PHP开发mybatisをエレガントに使用する

Mybatis は、初期段階で使用するのが非常に面倒です。さまざまな設定ファイル、エンティティ クラス、dao レイヤー マッピングの関連付け、その他多くの設定が必要です。もちろん、mybatis も初期段階でこの欠点を発見し、テーブルの結果に基づいてエンティティ クラス、構成ファイル、DAO レイヤー コードを自動的に生成できるジェネレーターを開発しました。これにより、後の開発作業負荷の一部が軽減されます。アノテーションを使用したり、DAO を自動的に管理したりするための多くの最適化も行われ、レイヤーや設定ファイルなどが開発されました。これが今日説明するモデルです。 +mybatis は、設定ファイルなしで完全にアノテーションを付けることができ、簡単に設定して簡単に使用できます。

ここで Spring Boot について考えてみましょう。Spring Boot に関連するものはすべて複雑さを単純化します。

mybatis-spring-boot-starter

公式説明: MyBatis Spring-Boot-Starter は、Spring Boot で MyBatis を使用するのに役立ちます
実際、myBatis は Spring Boot が非常に人気があることに気づき、その楽しみに参加するソリューションを開発しました。しかし、これにより多くの問題が解決され、よりスムーズに使用できるようになります。 mybatis-spring-boot-starter には主に 2 つの解決策があります。1 つはアノテーションを使用してすべての問題を解決する方法、もう 1 つは単純化された古い伝統です。

もちろん、どのモードでも最初に mybatis-spring-boot-starter の pom ファイルを導入する必要があります。現在の最新バージョンは 1.1.1 です

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.1.1</version></dependency>

さて、2 つの開発モードを別々に紹介しましょう

設定ファイルのアノテーションなしのバージョンです。

これですべてです。注釈を使用して完了します。

1 関連する Maven ファイルを追加します

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>1.1.1</version>
    </dependency>
     <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
     <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency></dependencies>

完全な pom パッケージはここには掲載されません

2. Application.properties 関連する設定を追加します

mybatis.type-aliases-package=com.neo.entity

spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8spring.datasource.username = root
spring.datasource.password = root

springboot は自動的に spring.datasource.* を読み込みます。関連する設定とデータ ソースは sqlSessionFactory に自動的に挿入され、sqlSessionFactory は Mapper に自動的に挿入されます。 ちなみに、何も心配する必要はなく、そのまま選択して使用します。

スタートアップ クラスでマッパー パッケージをスキャンするには @MapperScan を追加します

@SpringBootApplication@MapperScan("com.neo.mapper")public class Application {    
public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

。または、Mapper クラスに直接アノテーション @Mapper を追加します。それ以外の場合、各マッパーにアノテーションを追加するのは非常に面倒になります。

3. マッパーの開発

3 番目のステップは最も重要なステップです。SQL 生成はすべてここにあります

public interface UserMapper {

    @Select("SELECT * FROM users")
    @Results({
        @Result(property = "userSex",  column = "user_sex", javaType = UserSexEnum.class),
        @Result(property = "nickName", column = "nick_name")
    })
    List<UserEntity> getAll();

    @Select("SELECT * FROM users WHERE id = #{id}")
    @Results({
        @Result(property = "userSex",  column = "user_sex", javaType = UserSexEnum.class),
        @Result(property = "nickName", column = "nick_name")
    })
    UserEntity getOne(Long id);

    @Insert("INSERT INTO users(userName,passWord,user_sex) VALUES(#{userName}, #{passWord}, #{userSex})")
    void insert(UserEntity user);

    @Update("UPDATE users SET userName=#{userName},nick_name=#{nickName} WHERE id =#{id}")
    void update(UserEntity user);

    @Delete("DELETE FROM users WHERE id =#{id}")
    void delete(Long id);

}

# 記号と $ 記号の使用の違いに注意してください:

// This example creates a prepared statement, something like select * from teacher where name = ?;
@Select("Select * from teacher where name = #{name}")
Teacher selectTeachForGivenName(@Param("name") String name);

// This example creates n inlined statement, something like select * from teacher where name = &#39;someName&#39;;
@Select("Select * from teacher where name = &#39;${name}&#39;)
Teacher selectTeachForGivenName(@Param("name") String name);

4.関連する dao 層の開発は基本的に完了しています。使用するときは、通常のクラスとして注入するだけです

@RunWith(SpringRunner.class)@SpringBootTestpublic class UserMapperTest {    @Autowired
    private UserMapper UserMapper;    @Test
    public void testInsert() throws Exception {
        UserMapper.insert(new UserEntity("aa", "a123456", UserSexEnum.MAN));
        UserMapper.insert(new UserEntity("bb", "b123456", UserSexEnum.WOMAN));
        UserMapper.insert(new UserEntity("cc", "b123456", UserSexEnum.WOMAN));

        Assert.assertEquals(3, UserMapper.getAll().size());
    }    @Test
    public void testQuery() throws Exception {
        List<UserEntity> users = UserMapper.getAll();
        System.out.println(users.toString());
    }    @Test
    public void testUpdate() throws Exception {
        UserEntity user = UserMapper.getOne(3l);
        System.out.println(user.toString());
        user.setNickName("neo");
        UserMapper.update(user);
        Assert.assertTrue(("neo".equals(UserMapper.getOne(3l).getNickName())));
    }
}

ミニマリスト XML バージョン

ミニマリスト XML バージョンは、マッピング ファイルの古い伝統を維持しており、最適化は主に実装層に反映されます。 dao を実装する必要はありません。システムはメソッド名によってマッピング ファイル内の対応する SQL を自動的に見つけます。

1、配置

pom文件和上个版本一样,只是application.properties新增以下配置

mybatis.config-locations=classpath:mybatis/mybatis-config.xm

mybatis.config-locations=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

指定了mybatis基础配置文件和实体类映射文件的地址

mybatis-config.xml 配置

<configuration>
    <typeAliases>
        <typeAlias alias="Integer" type="java.lang.Integer" />
        <typeAlias alias="Long" type="java.lang.Long" />
        <typeAlias alias="HashMap" type="java.util.HashMap" />
        <typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
        <typeAlias alias="ArrayList" type="java.util.ArrayList" />
        <typeAlias alias="LinkedList" type="java.util.LinkedList" />
    </typeAliases></configuration>

这里也可以添加一些mybatis基础的配置

2、添加User的映射文件

<mapper namespace="com.neo.mapper.UserMapper" >
    <resultMap id="BaseResultMap" type="com.neo.entity.UserEntity" >
        <id column="id" property="id" jdbcType="BIGINT" />
        <result column="userName" property="userName" jdbcType="VARCHAR" />
        <result column="passWord" property="passWord" jdbcType="VARCHAR" />
        <result column="user_sex" property="userSex" javaType="com.neo.enums.UserSexEnum"/>
        <result column="nick_name" property="nickName" jdbcType="VARCHAR" />
    </resultMap>

    <sql id="Base_Column_List" >
        id, userName, passWord, user_sex, nick_name    </sql>

    <select id="getAll" resultMap="BaseResultMap"  >
       SELECT 
       <include refid="Base_Column_List" />
       FROM users    </select>

    <select id="getOne" parameterType="java.lang.Long" resultMap="BaseResultMap" >
        SELECT 
       <include refid="Base_Column_List" />
       FROM users
       WHERE id = #{id}
    </select>

    <insert id="insert" parameterType="com.neo.entity.UserEntity" >
       INSERT INTO 
               users
               (userName,passWord,user_sex) 
           VALUES
               (#{userName}, #{passWord}, #{userSex})    </insert>

    <update id="update" parameterType="com.neo.entity.UserEntity" >
       UPDATE 
               users 
       SET 
           <if test="userName != null">userName = #{userName},</if>
           <if test="passWord != null">passWord = #{passWord},</if>
           nick_name = #{nickName}
       WHERE 
               id = #{id}
    </update>

    <delete id="delete" parameterType="java.lang.Long" >
       DELETE FROM
                users 
       WHERE 
                id =#{id}
    </delete></mapper>

其实就是把上个版本中mapper的sql搬到了这里的xml中了

3、编写Dao层的代码

public interface UserMapper {

    List<UserEntity> getAll();

    UserEntity getOne(Long id);

    void insert(UserEntity user);

    void update(UserEntity user);

    void delete(Long id);

}

对比上一步这里全部只剩了接口方法

如何选择

两种模式各有特点,注解版适合简单快速的模式,其实像现在流行的这种微服务模式,一个微服务就会对应一个自已的数据库,多表连接查询的需求会大大的降低,会越来越适合这种模式。

老传统模式比适合大型项目,可以灵活的动态生成SQL,方便调整SQL,也有痛痛快快,洋洋洒洒的写SQL的感觉。


声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

VSCode Windows 64 ビットのダウンロード

VSCode Windows 64 ビットのダウンロード

Microsoft によって発売された無料で強力な IDE エディター

DVWA

DVWA

Damn Vulnerable Web App (DVWA) は、非常に脆弱な PHP/MySQL Web アプリケーションです。その主な目的は、セキュリティ専門家が法的環境でスキルとツールをテストするのに役立ち、Web 開発者が Web アプリケーションを保護するプロセスをより深く理解できるようにし、教師/生徒が教室環境で Web アプリケーションを教え/学習できるようにすることです。安全。 DVWA の目標は、シンプルでわかりやすいインターフェイスを通じて、さまざまな難易度で最も一般的な Web 脆弱性のいくつかを実践することです。このソフトウェアは、

SublimeText3 Linux 新バージョン

SublimeText3 Linux 新バージョン

SublimeText3 Linux 最新バージョン

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

MantisBT

MantisBT

Mantis は、製品の欠陥追跡を支援するために設計された、導入が簡単な Web ベースの欠陥追跡ツールです。 PHP、MySQL、Web サーバーが必要です。デモおよびホスティング サービスをチェックしてください。