乐趣区

关于mybatis:mybatis-学习记录-一

一、Mybatis HelloWorld

1. 应用 Maven 创立一个我的项目, 我的项目目录如下

2. 在 maven 的 pom.xml 引入依赖

次要包含 mybatis,mysql,junit 的依赖,而后就可进行开发了。

<?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>test03</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.22</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

3. 编写 mybatis 配置文件 mybatis-config.xml 文件

次要是用来配置数据源 和 配置相干 mapper*.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">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/test?serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="UserMapper.xml"/>
    </mappers>
</configuration>

4. 创立用户表, 编写 User 类

package com.jt;

public class User {
    private int id;
    private String username;
    private String password;

    public int getId() {return id;}

    public void setId(int 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;}

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

5. 编写 UserMapper 类

package com.jt;

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.Map;

public interface  UserMapper {public User selectUser(int id);
   public User  selectUserByIdAndName(@Param("id") Integer id,@Param("username") String username);
   public User  selectUserByIdAndNameUseMap(Map map);

   public Integer insertUser(User user);
   public boolean updateUser(User user);
   public Integer deleteUserById(int id);
}

6. 编写 UserMapper.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.jt.UserMapper">
    <select id="selectUser" resultType="com.jt.User">
        select * from test01 where id = #{id}
    </select>
    <select id="selectUserByIdAndName" resultType="com.jt.User">
        select * from test01 where id = #{id} and username=#{username}
    </select>
    <select id="selectUserByIdAndNameUseMap" resultType="com.jt.User">
        select * from test01 where id = #{id} and username=#{username}
    </select>
    <insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
        insert into test01 (username,password) values(#{username},#{password})
    </insert>
    <update id="updateUser" parameterType="com.jt.User">
        update test01 set username=#{username} where id=#{id}
    </update>
    <delete id="deleteUserById">
        delete from test01 where id=#{id}
    </delete>
</mapper>

7. 编写测试类

import com.jt.User;
import com.jt.UserMapper;
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.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.Map;

public class HelloTest {
    @Test
    public void selectTest() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory =
                new SqlSessionFactoryBuilder().build(inputStream);
        try (SqlSession session = sqlSessionFactory.openSession()) {UserMapper userMapper = session.getMapper(UserMapper.class);
            User user = userMapper.selectUser(1);
            System.out.println(user);
        }finally {sqlSessionFactory.openSession();
        }

    }
    @Test
    public void selectByIdAndNameTest() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory =
                new SqlSessionFactoryBuilder().build(inputStream);
        try (SqlSession session = sqlSessionFactory.openSession()) {UserMapper userMapper = session.getMapper(UserMapper.class);
            User user = userMapper.selectUserByIdAndName(5,"3");
            System.out.println(user);
        }finally {sqlSessionFactory.openSession();
        }

    }
    @Test
    public void selectByIdAndNameUseMapTest() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory =
                new SqlSessionFactoryBuilder().build(inputStream);
        try (SqlSession session = sqlSessionFactory.openSession()) {UserMapper userMapper = session.getMapper(UserMapper.class);
            Map map = new LinkedHashMap();
            map.put("id",5);
            map.put("username","3");

            User user = userMapper.selectUserByIdAndNameUseMap(map);
            System.out.println(user);
        }finally {sqlSessionFactory.openSession();
        }

    }

    @Test
    public void insertTest() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory =
                new SqlSessionFactoryBuilder().build(inputStream);
        try (SqlSession session = sqlSessionFactory.openSession()) {UserMapper userMapper = session.getMapper(UserMapper.class);
            User user01 = new User();
            user01.setUsername("4");
            user01.setPassword("4");
            userMapper.insertUser(user01);
            System.out.println(user01.getId());

        }finally {sqlSessionFactory.openSession();
        }
    }
    @Test
    public void updateTest() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory =
                new SqlSessionFactoryBuilder().build(inputStream);
        try (SqlSession session = sqlSessionFactory.openSession()) {UserMapper userMapper = session.getMapper(UserMapper.class);
            User user01 = new User();
            user01.setId(2);
            user01.setUsername("批改 1");

            boolean res = userMapper.updateUser(user01);
            System.out.println(res);

        }finally {sqlSessionFactory.openSession();
        }
    }
    @Test
    public void deleteTest() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory =
                new SqlSessionFactoryBuilder().build(inputStream);
        try (SqlSession session = sqlSessionFactory.openSession()) {UserMapper userMapper = session.getMapper(UserMapper.class);


           int res =  userMapper.deleteUserById(1);
            System.out.println(res);

        }finally {sqlSessionFactory.openSession();
        }
    }
}
退出移动版