LoginSignup
0
0

More than 3 years have passed since last update.

【Mybatis勉強ノート01】MyBatis crud

Posted at

JDBC データベースの検索

image.png

image.png
image.png

JDBCの問題

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

Mybatis quick start

開発環境の準備

database情報源

image.png

Mavenプロジェクトの構造

image.png
名前、フォルダ構造は完全に同じである必要があります.

pom.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 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

User.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


        select *
        from user where "${colname}" like '${pattern}';

colname and pattern are variable.


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

IUserDao.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

IUserDao.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

MyBatisTest.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

testFindAllの結果

image.png

testFindUserByIdの結果

image.png

testSaveUserの結果

image.png

testUpdateUserの結果

image.png

testDeleteUserの結果

image.png
image.png

testQueryVoの結果

image.png
image.png

testCountFuncの結果

image.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0