1 Quickly build mybatis project

1.1 Using Maven's quickstart framework

        Note that the quickstart of w does not appear:

 1.2 Add dependencies

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

    <!--mybatis依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.1</version>
    </dependency>

    <!--mysql驱动-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.9</version>
    </dependency>
 </dependencies>

1.3 Introducing plugins

<build>
    <!--资源插件:处理src/main/java目录中的xml-->
  <resources>
    <resource>
      <directory> src/main/java</directory> <!--所在的目录-->
      <includes><!--包括目录下的.properties,.xml文件都会扫描到-->
        <include>**/*.properties</include>
        <include>**/*.xml</include>
      </includes>
      <filtering>false</filtering>
    </resource>
  </resources>
  </build>

        Note that the dao xml file can only be loaded into the target classes after the plug-in is added:

 1.4 Create a Student entity class in the pojo package

package jiang.pojo;

public class Student {
    private Integer id;
    private String name;
    private Integer age;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

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

    public Student(Integer id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public Student() {
    }
}

1.5 Create the corresponding Student database

1.6 Create the StudentDao interface in the dao package

package jiang.dao;

import jiang.pojo.Student;

public interface StudentDao {
    Student selectStudentById(Integer id);
}

1.7 Create a StudentDao.xml file in the dao package

        Note: namespace, id, and resultType need to be modified; do not write semicolon after the sql statement;

<?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="jiang.dao.StudentDao"><!--namespace、id、resultType都需要修改-->
    <select id="selectStudentById" resultType="jiang.pojo.Student"> 
        <!--查询一个学生Student
            <select>:表示查询操作,里面的select
            id:要执行的sql语句的唯一表示。是一个自定义的字符串。
                推荐使用dao接口中的方法名称
            resultType:告诉mybatis,执行sql语句,把数据赋值给那个类型的java对象。
                resultType的值现在使用的java对象的全限定名称,从java路径后开始写包路径
          -->
        SELECT * FROM student where id = 1
    </select>
</mapper>

1.8 Create resources resource package in main

1.9 Create mybatis.xml main configuration file in resources

        Part to modify:

        1. <property name="url" value="jdbc:mysql://localhost:3306/ study ?useUnicode=true&characterEncoding=utf-8"/>      study is the name of the database!

        2.<mapper resource="jiang/dao/StudentDao.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"/>
            <!--配置数据源:创建connection对象。-->
            <dataSource type="POOLED">
                <!--driver:驱动的内容-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <!--url:连接数据库的url-->
                <property name="url" value="jdbc:mysql://localhost:3306/study?useUnicode=true&amp;characterEncoding=utf-8"/>
                <!--用户名-->
                <property name="username" value="root"/>
                <!--密码-->
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <!--指定其他mapper文件的位置:找到其他文件的sql语句-->
    <mappers>
        <!--使用mapper的resource属性指定mapper文件路径
        这个路径是从target/classes路径开启的
        使用注意:
        resoruce="mapper文件的路径,使用/分割路径"
        一个mapper resource指定一个mapper文件
        -->
        <mapper resource="jiang/dao/StudentDao.xml"/>
    </mappers>
</configuration>

 1.10 Create test content

package jiang;

import jiang.pojo.Student;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import org.apache.ibatis.io.Resources;


import java.io.IOException;
import java.io.InputStream;

public class MyTest {
    @Test
    public void test1() throws IOException {
        //调用mybatis某个对象的方法,执行mapper文件中的sql语句
        // mybatis核心类:sqlsessionFactory
        //1.定义mybatis主配置文件的位置,从类路径开始的相对路径
        String config = "mybatis.xml";
        //2.读取主配置文件。使用mybatis框架中的Resources类
        InputStream inputStream = Resources.getResourceAsStream(config);
        //3.创建SqlSessionFactory对象,使用sqlSessionFactoryBuidler类
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
        //4.获取SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //5.指定要执行的sql语句的id
        // sql的id = namespace+"."+ selectlupdate|insert |delete标签的id属性值(接口的方法名)
        String sqlId = "jiang.dao.StudentDao"+"."+"selectStudentById";
        //6.通过SqlSession方法,执行sql语句
        Student student = sqlSession.selectOne(sqlId);
        System.out.print("使用mybatis查询一个学生:"+student);
        //7.关闭SqlSession对象
        sqlSession.close();
    }
}

        The result of the operation is as follows:

1.11 Common Mistakes and Notes

a. The first line of the main configuration file cannot be empty, otherwise an error will be reported:

org.apache.ibatis.exceptions.PersistenceException: 
### Error building SqlSession.
### Cause: org.apache.ibatis.builder.BuilderException: Error creating document instance. Cause: org.xml.sax.SAXParseException; lineNumber: 2 ; columnNumber: 6; Processing instruction targets matching "[xX][mM][lL]" are not allowed.

Guess you like

Origin blog.csdn.net/no996yes885/article/details/131885548