【Mybatis勉強ノート01】MyBatis crud

#JDBC データベースの検索
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1104888/ec26eb80-b1de-f657-3870-8e804a2b8c91.png)


![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1104888/eb2e7e61-5807-f1f4-165c-e4619fed10c8.png)
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1104888/8263e68d-2856-b3d0-c554-c0604e1622f4.png)

#JDBCの問題
1. データベースリンクの頻繁な作成とリリースは、システムリソースの浪費を招き、システムのパフォーマンスに影響を与えます。しかし、データベース接続プールを使用することで、この問題を解決することができます。
2. sqlステートメントはコードにハードコーディングされているため、コードの保守が困難です.

# Mybatis quick start

## 開発環境の準備

### database情報源
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1104888/17d0c287-1e7f-d524-26a4-42346c8a68d9.png)


### Mavenプロジェクトの構造
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1104888/c564339a-ccd5-5856-588d-6f54dcf12232.png)
名前、フォルダ構造は完全に同じである必要があります.

#### pom.xml
```xml
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>mybatis_01</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>xml_config_mybatis</module>
        <module>annotation_mybatis</module>
    </modules>
    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.23</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>
    <properties>
        <maven.compiler.source>14</maven.compiler.source>
        <maven.compiler.target>14</maven.compiler.target>
    </properties>

</project>


```


###mybatisを設定する
#### SqlMapConfig.xml
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">


<!-- mybatis main config file -->
<configuration>
    <properties resource="jdbc.properties">

    </properties>
    <typeAliases>
        <package name="com.xml_config.domain"/>
    </typeAliases>
    <!-- config environment -->
    <environments default="mysql">
        <!-- config mysql environment-->
        <environment id="mysql">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>

    <!-- config mappers -->
    <mappers>
         <mapper resource="com/xml_config/dao/IUserDao.xml"/>
    </mappers>
</configuration>
```


## pojo objectの準備
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1104888/e420dbdb-5efe-1048-1645-d134b5169c96.png)

### User.java

```java
package com.xml_config.domain;

import java.io.Serializable;
import java.util.Date;

public class User implements Serializable {

    private Integer id;
    private String username;
    private Date birthday;
    private String gender;
    private String addr;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getAddr() {
        return addr;
    }

    public void setAddr(String addr) {
        this.addr = addr;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", birthday=" + birthday +
                ", gender='" + gender + '\'' +
                ", addr='" + addr + '\'' +
                '}';
    }
}

```

### QueryVo.java
It's just like sql

```sql

        select *
        from user where "${colname}" like '${pattern}';
```
colname and pattern are variable.

```java

package com.xml_config.domain;

import java.io.Serializable;

public class QueryVo implements Serializable {
    private String colName;
    private String pattern;

    public String getColName() {
        return colName;
    }

    public void setColName(String colName) {
        this.colName = colName;
    }

    public String getPattern() {
        return pattern;
    }

    public void setPattern(String pattern) {
        this.pattern = pattern;
    }
}


```

## pojo object mapperの準備

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1104888/d5718bea-5ba8-2eb6-bbf3-41bcbdda9075.png)

IUserDao.java

```java
package com.xml_config.dao;

import com.xml_config.domain.QueryVo;
import com.xml_config.domain.User;

import java.util.List;

public interface IUserDao {

    List<User> findAll();
    void saveUser(User user);
    int updateUser(User user);
    User findUserById(int id);
    int deleteUser(int id);
    List<User> findByVo(QueryVo vo);
    int findCounts();
}

```




## xmlを使用してmapperを設定
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1104888/f72ba723-ff6b-92da-dcd5-176b2581910e.png)

### IUserDao.xml

```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.xml_config.dao.IUserDao">
    <resultMap id="userResultMap" type="com.xml_config.domain.User">
        <id property="id" column="id"/>
        <result property="username" column="username"/>
        <result property="birthday" column="birthday"/>
        <result property="gender" column="sex"/>
        <result property="addr" column="address"/>
    </resultMap>


    
    <!--findAll-->
    <select id="findAll" resultMap="userResultMap">
        select *
        from user
    </select>
    <!--    findById -->
    <select id="findUserById" resultMap="userResultMap" parameterType="int">
        select *
        from user
        where id = #{id}
    </select>
    <!--    insert one user  -->
    <insert id="saveUser" parameterType="com.xml_config.domain.User">
        -- return incremented id
        <selectKey resultType="int" keyColumn="id" keyProperty="id">
            select last_insert_id();
        </selectKey>
        insert into user (username,birthday,sex,address) values (#{username},#{birthday},#{sex},#{address} )
    </insert>
    <!--    update user -->
    <update id="updateUser" parameterType="com.xml_config.domain.User" >
        update user set username = #{username} , birthday= #{birthday}, sex = #{gender}, address = #{addr}  where id = #{id};
    </update>
<!--    delete user-->
    <delete id="deleteUser" parameterType="int">
        delete from user where id = #{id}
    </delete>
<!--    find by multiple statements  -->
    <select id="findByVo" resultType="com.xml_config.domain.User" parameterType="com.xml_config.domain.QueryVo">
        select *
        from user where ${colName} like #{pattern};
    </select>
<!--   find user numbers -->
    <select id="findCounts" resultType="int">
        select count(id) from user
    </select>
</mapper>
```



## test
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1104888/c16195fa-c8cf-67c4-4fda-877f87388762.png)

MyBatisTest.java

```java
import com.xml_config.dao.IUserDao;
import com.xml_config.domain.QueryVo;
import com.xml_config.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;




public class MybatisTest {
    String resource;
    InputStream in;
    SqlSessionFactory factory;
    SqlSession session;
    IUserDao userDao;


    @Before
    public void init() throws IOException {
        //1　read mybatis config file
        resource = "SqlMapConfig.xml";
        in = Resources.getResourceAsStream(resource);
        //2.create SqlSessionFactory(using your mybatis config)
        factory = new SqlSessionFactoryBuilder().build(in);
        //3.use factory create SqlSession object
        session = factory.openSession();
        //4.use SqlSession create Dao Interface's proxy object
        userDao = session.getMapper(IUserDao.class);
    }

    @After
    public void destroy() throws IOException {
        session.commit();
        in.close();
        session.close();
    }


    @Test
    public void testFindAll() throws IOException {

        //use proxy object to excute methods
        List<User> users = userDao.findAll();
        for(User user : users){
            System.out.println(user);
        }
    }

    @Test
    public void testFindUserById() {
        int id = 48;
        User user = userDao.findUserById(id);
        System.out.println(user);
    }

    @Test
    public void testSaveUser() {
        User user = new User();
        user.setUsername("test1");
        user.setAddr("ssss");
        user.setGender("M");
        user.setBirthday(new Date());
        System.out.println("before" + user);
        userDao.saveUser(user);
        System.out.println("after" + user);
    }

    @Test
    public void testUpdateUser() {
        User user = userDao.findUserById(50);
//        System.out.println(user);
        user.setBirthday(new Date());
        user.setUsername("update test");
        user.setAddr("sssdsads");
       int res =  userDao.updateUser(user);
        System.out.println(res);
    }

    @Test
    public void testDeleteUser() {
        int res = userDao.deleteUser(49);
        System.out.println(res);
    }

    @Test
    public void testQueryVo() {
        QueryVo vo = new QueryVo();
        vo.setColName("username");
        vo.setPattern("_王");
        List<User> users = userDao.findByVo(vo);
        System.out.println(users);
    }

    @Test
    public void testCountFunc() {
        System.out.println(userDao.findCounts());
    }
}

```
### 現在のデータベースのデータ
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1104888/b2b03555-f396-b05b-b359-b6893828d3e4.png)


### testFindAllの結果

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1104888/3d8dbfc5-f8dc-fdfa-208d-30ab7bb17751.png)

### testFindUserByIdの結果
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1104888/c2afc303-36a5-9c29-988e-b6d575c668d1.png)


### testSaveUserの結果
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1104888/ba2c70fa-c79b-3829-7431-1aeb3ab3eccf.png)

### testUpdateUserの結果
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1104888/c8760b09-0c81-c878-e7ac-1e3614ee439d.png)

### testDeleteUserの結果
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1104888/ee57b08d-099d-b0b9-7b31-8cba126bcdfb.png)
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1104888/976379a5-02a4-ef70-08a4-1c4f8f079aa9.png)

### testQueryVoの結果
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1104888/b3358f64-514e-3a68-8b90-711ffaa6168f.png)
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1104888/ec515873-4366-b480-509e-eb61744bb306.png)

### testCountFuncの結果
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1104888/ee344597-639b-a313-fef7-66f66eed521e.png)