Mybatis 简单试用

1. 创建项目

IDEA创建一个基本的maven项目。
导入依赖:


<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.0modelVersion>

    <groupId>org.examplegroupId>
    <artifactId>MybatisTestartifactId>
    <packaging>pompackaging>
    <version>1.0-SNAPSHOTversion>
    <modules>
        <module>Test01module>
    modules>

    <properties>
        <maven.compiler.source>11maven.compiler.source>
        <maven.compiler.target>11maven.compiler.target>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    properties>

    <dependencies>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.33version>
        dependency>

        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.13version>
        dependency>

    dependencies>

    
    <build>
        <resources>
            <resource>
                <directory>src/main/resourcesdirectory>
                <includes>
                    <include>**/*.xmlinclude>
                    <include>**/*.propertiesinclude>
                includes>
                <filtering>falsefiltering>
            resource>

            <resource>
                <directory>src/main/javadirectory>
                <includes>
                    <include>**/*.xmlinclude>
                    <include>**/*.propertiesinclude>
                includes>
                <filtering>falsefiltering>
            resource>
        resources>
    build>

project>

这里导入了mysql-connector-java和mybatis。此外注意build标签中内容很重要,见我之前一篇:https://blog.csdn.net/awangdea99/article/details/132256100?spm=1001.2014.3001.5501

2. User实体类

在我的本地MySQL中创建了一个名mybatis的数据库,然后创建了一个名为usertable的表,其中放了id、name、pwd三个字段。
Mybatis 简单试用_第1张图片

因此我们需要搞个对应的实体类:

package com.wonder.entity;

public class User {
  private long id;
  private String name;
  private String pwd;


  public long getId() {
    return id;
  }

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


  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }


  public String getPwd() {
    return pwd;
  }

  public void setPwd(String pwd) {
    this.pwd = pwd;
  }

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

3. 创建一个简单的mybatis工具类

package com.wonder.utils;

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 java.io.IOException;
import java.io.InputStream;

//Mabatis工具类
public class MybatisUtils {
    static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            //读取mybatis配置文件(放在resource目录下,官方例子使用的文件名为mybatis-config.xml)
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //唯一开放方法:获取一个SqlSession
    public static SqlSession getSession(){
        //通过sqlSessionFactory创建SqlSession
        return sqlSessionFactory.openSession();
    }

}

4. 创建mybatis配置文件

在resources目录下创建mybatis配置文件(mybatis-config.xml),名字和工具类当中的resource一样。


DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://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/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            dataSource>
        environment>
    environments>
    <mappers>
        
        
        <mapper resource="com/wonder/dao/UserMapper.xml"/>
    mappers>
configuration>

由于我需要连接我本地的mybatis数据库,所以需要driver、url、username、password配置,和JDBC差不多(毕竟mybatis就是基于jdbc的)。注意我这个url不太规范,还需要加一些后缀防止风险。

在mapper配置中使用resource映射到了com/wonder/dao/UserMapper.xml文件,这个是下一步我们要创建的(其实应该写完dao和mapper.xml后再回来加入这个配置)。

5. 写dao层接口和Mapper.xml

创建dao目录。创建一个dao接口UserMapper(传统dao接口一般以Dao结尾,如UserDao,但mybatis建议使用Mapper结尾)

package com.wonder.dao;

import com.wonder.entity.User;

import java.util.List;

//自定义的dao层接口
public interface UserMapper {
    List<User> getUserList();
    User getUserByID(int id);
}

创建与之对应的Mapper.xml,文件名是UserMapper.xml(这就是我们上一步mybatis配置文件中mapper所映射的文件,名字可以随便起,但一般建议跟dao层的mapper一致)


DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.wonder.dao.UserMapper">
    
    <select id="getUserList" resultType="com.wonder.entity.User">
        select * from usertable
    select>
    
    <select id="getUserByID" parameterType="int" resultType="com.wonder.entity.User">
        select * from usertable where id = #{id}
    select>
mapper>

6. 写个测试类测试

package com.wonder.dao;

import com.wonder.entity.User;
import com.wonder.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;


//测试类。
public class UserMapperTest {
    @Test
    public void getUserList() {
        //官方推荐把获得的SqlSession用完即释放,所以放在try语句的括号中。
        try(SqlSession session = MybatisUtils.getSession()){
            UserMapper mapper = session.getMapper(UserMapper.class);
            List<User> userList = mapper.getUserList();
            for (User user : userList) {
                System.out.println(user.toString());
            }
        }
    }

    @Test
    public void getUserByID() {
        //官方推荐把获得的SqlSession用完即释放,所以放在try语句的括号中。
        try(SqlSession session = MybatisUtils.getSession()){
            UserMapper mapper = session.getMapper(UserMapper.class);
            User user = mapper.getUserByID(2);
            System.out.println(user.toString());
        }
    }
}

依次执行两个方法,试一下效果就出来了。
Mybatis 简单试用_第2张图片
Mybatis 简单试用_第3张图片

你可能感兴趣的:(【框架】Mybatis,mybatis)