其他分享
首页 > 其他分享> > MyBatis:QuickStart

MyBatis:QuickStart

作者:互联网

MyBatis:QuickStart

  1. 创建一个Maven工程,可采用模板:Create from archetype—>maven-archetype-webapp

  2. 在pom.xml描述文件中添加依赖:https://search.maven.org/

    完整的pom.xml在本条最后,在其之前,对依赖进行了解释以及对<resources>进行了一些补充

  • 必要
    • org.mybatis:mybatis:3.5.7
    • mysql:mysql-connector-java:8.0.25
  • 非必要
    • org.projectlombok:lombok:1.18.20

mybatis

The MyBatis SQL mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor or annotations. Simplicity is the biggest advantage of the MyBatis data mapper over object relational mapping tools.

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.7</version>
</dependency>

MySQL Connector/J

JDBC Type 4 driver for MySQL

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.25</version>
</dependency>

Project Lombok

Spice up your java: Automatic Resource Management, automatic generation of getters, setters, equals, hashCode and toString, and more!

  • 使用步骤
    • File->Settings->Plugins->在Marketplace中搜索lombok下载安装。
    • pom.xml文件中配置lombok的依赖
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.20</version>
</dependency>

表示读取该目录的所有文件

示例:

<resource>
    <directory>src/main/resources</directory>
</resource>

includes表示仅读取directory文件夹下includes中指定的文件或文件夹的内容,,即in的意思

<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
        </resource>
    </resources>
</build>

excludes表示读取directory文件夹下但排除includes中指定的文件或文件夹的所有其他内容,即not in的意思。

示例:

<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <excludes>com.ywx.config/*.xml</excludes>
        </resource>
    </resources>
</build>

完整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>com.ywx</groupId>
    <artifactId>ywxmybatis</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>ywxmybatis Maven Webapp</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

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

    <dependencies>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

    </dependencies>


    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>

</project>

  1. 建立一张数据表emp

    create database if not exists dbmybatis character set utf8;
    use dbmybatis;
    
    create table emp(
    	id int primary key auto_increment,
    	name varchar(20),
    	sal double
    );
    
    select * from emp;
    
  2. 建立数据表对应的实体类

    在pom中导入org.projectlombok:lombok:1.18.20依赖并下载插件,就可以实现:

    自动生成getter、setter、equals、hashCode和toString等等。

package com.ywx.entity;

import lombok.Data;

@AllArgsConstructor
@NoArgsConstructor
@Data
public class Emp {
    private long id;
    private String name;
    private Double sal;
}

  1. 创建MyBatis的配置文件xxx.xml,文件名自定义,因为在使用的时候是需要提供配置名称的。

    • 为了统一,这里使用MyBatisConfig.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">
    
    1. 在该配置文件中配置MyBatis的运行环境,配置事务管理、数据源

      <?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>
          <!-- 配置MyBatis的运行环境 -->
          <environments default="chooseMysql">
              <environment id="chooseMysql">
                  <!-- 配置JDBC事务管理 -->
                  <transactionManager type="JDBC"></transactionManager>
                  <!-- 配置事务管理、数据源 -->
                  <!-- POOLED配置JDBC数据源连接池 -->
                  <dataSource type="POOLED">
                      <property name="driver" value="com.mysql.cj.jdbc.Driver"></property>
                      <property name="url" value="jdbc:mysql://localhost:3306/dbmybatis?useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=GMT%2B8"></property>
                      <property name="username" value="root"></property>
                      <property name="password" value="root"></property>
                  </dataSource>
              </environment>
          </environments>
      </configuration>
      
    2. 还需要在该配置文件中注册相应的Mapper.xml。

  2. 自定义接口,该接口定义相关的业务方法,CRUD

    package com.ywx.repository;
    
    import com.ywx.entity.Emp;
    
    import java.util.List;
    
    public interface EmpRepository {
        public int insert(Emp emp);
        public int update(Emp emp);
        public int deleteById(long id);
        public List<Emp> findAll();
        public Emp findById();
    }
    
    
  3. 为每个要去映射的类创建对应的Mapper.xml文件,来定义并且管理这个对象数据的SQL。

    该配置文件的约束头

    <?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特性通常设置为包名+该文件名来唯一确定该Mapper

      • insert 标签表示执⾏添加操作

      • select 标签表示执⾏查询操作

      • update 标签表示执⾏更新操作

      • delete 标签表示执⾏删除操作

      • 特性id为自定义接口中的成员方法名,可能会被解析为实现类中的对应方法,通过namespace+id组合可以来唯一确定该条SQL语句

      • 特性parameterType是调用该方法时传入的参数类型

      • 特性resultType是查询到的反射结果,因为是ORM,所以返回结果为集合时意味着是被包装了一次,实际返回结果是对应的单个类。(表述不准确)

      • 更多特性放到下一节中总结

    <?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.ywx.repository.EmpRepository">
        <insert id="insert" parameterType="com.ywx.entity.Emp">
            insert into emp (name,sal) values(#{name},#{sal})
        </insert>
    </mapper>
    
  4. MyBatisConfig.xml中注册Mapper.xml

    resource中注意格式,因为并不是类,而是xxx.xml文件,我们在生成的target中需要为资源指定路径,故这样书写。

        <mappers>
            <mapper resource="com/ywx/repository/EmpRepository.xml"></mapper>
        </mappers>
    
  5. 测试代码

package com.ywx.test;

import com.ywx.entity.Emp;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

public class Test {
    public static void main(String[] args) {
        InputStream inputStream = Test.class.getClassLoader().getResourceAsStream("MyBatisConfig.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new  SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        String statement = "com.ywx.repository.EmpRepository.insert";
        Emp emp = new Emp(3L,"张三",3555D);
        int result = sqlSession.insert(statement, emp);
        System.out.println(result);
        sqlSession.commit();
        sqlSession.close();
    }
}

  1. 我们发现,现在我们为每一个数据表都需要去创建一个对应的Mapper.xml文件去进行管理。当我们使用Mapper代理实现自定义接口的时候,就会由框架自动去生成接口的代理对象

    1. 自定义接口,该接口定义相关的业务方法,CRUD

      package com.ywx.entity;
      
      import lombok.AllArgsConstructor;
      import lombok.Data;
      import lombok.NoArgsConstructor;
      
      @Data
      @AllArgsConstructor
      @NoArgsConstructor
      public class Account {
          private long id;
          private String username;
          private String password;
          private int age;
      }
      
      
    2. 创建接口对应的Mapper文件,来为接口中中方法定义SQL。

      MyBatis为什么可以自动创建接口的代理对象呢?

      肯定需要你在约束的配置文件里给出生成代理对象的必要信息和一定的规则

      1. 约束头:注意和前面原生接口的约束头不同

        <?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">
        
      2. 为了自动创建接口的代理对象的规则

        • namespace使用全类名(使用原生接口的时候并没有强制要求,此处为强制要求)
        • 其余和使用原生接口没什么不同,看上面的内容
      3. 示例

        <?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.ywx.repository.EmpRepository">
            <select id="findAll" resultType="com.ywx.entity.Emp" >
              select * from emp
            </select>
        </mapper>
        
    3. MyBatisConfig.xml中注册Mapper.xml

      <mappers>
          <mapper resource="com/ywx/mapper/EmpRepositoryMapper.xml"></mapper>
      </mappers>
      
    4. 测试,与原生接口不同的是,可以直接调用接口的代理对象

      建议使用测试单元来测试每个接口方法

      @Before&@After&@Test配合

    package com.ywx.test;
    
    import com.ywx.entity.Emp;
    import com.ywx.repository.EmpRepository;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    
    import java.io.InputStream;
    import java.util.List;
    
    public class Test2 {
        public static void main(String[] args) {
            InputStream resourceAsStream = Test2.class.getClassLoader().getResourceAsStream("MyBatisConfig.xml");
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(resourceAsStream);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            EmpRepository empRepository = sqlSession.getMapper(EmpRepository.class);
            List<Emp> emps = empRepository.findAll();
            for (Emp emp:
                 emps) {
                System.out.println(emp);
            }
            sqlSession.close();
        }
    }
    
    

标签:xml,QuickStart,ywx,import,MyBatis,org,com,public
来源: https://blog.csdn.net/weixin_44728780/article/details/116984521