Basic introduction to MyBatis and quick start cases

 (2) Formerly known as ibatis, it was renamed MyBatis in
ibatis3
. Implement decoupling from Java programs
(5) mybatis is only responsible for SQL, and the work of building databases and tables is completed by programmers

 Quick start case

0. Project structure

1. Create a new java project and write maven dependencies

Pay attention to the resource configuration at the end of the configuration here, otherwise the mapping file will not be found.

There is a directory standard in the maven project. In addition to the standard resources directory, the xml file under src will not be output to the target/classes directory when building. Therefore, you can move the xml file to the resources directory (method 1), or The xml file under src is also added as a resource, so that it will also be output to the target/classes directory during construction (method 2).
 

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

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

    <dependencies>
<!--        mybatis核心包-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.15</version>
        </dependency>
<!--java字节码操作框架-->
        <dependency>
            <groupId>org.ow2.asm</groupId>
            <artifactId>asm</artifactId>
            <version>7.1</version>
        </dependency>
<!--生成和转换Java字节码的高级API。-->
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>3.3.0</version>
        </dependency>
<!---->
        <dependency>
            <groupId>ch.qos.reload4j</groupId>
            <artifactId>reload4j</artifactId>
            <version>1.2.25</version>
        </dependency>
<!--日志-->
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.3.0</version>
        </dependency>
<!--        -->
        <dependency>
            <groupId>ognl</groupId>
            <artifactId>ognl</artifactId>
            <version>3.4.2</version>
        </dependency>
<!--日志-->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.22.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.17.1</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
<!--        在Java中编辑字节码的类库-->
        <dependency>
            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.29.2-GA</version>
        </dependency>
<!--        作为各种日志框架的简单门面或抽象,允许最终用户在部署时插入所需的日志框架。-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>2.0.9</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.5</version>
        </dependency>
        <!--         拓展c3p0功能的mchange包 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>mchange-commons-java</artifactId>
            <version>0.2.9</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.caches</groupId>
            <artifactId>mybatis-ehcache</artifactId>
            <version>1.2.3</version>
        </dependency>
<!--        java本地缓存技术-->
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache-core</artifactId>
            <version>2.6.11</version>
        </dependency>

    </dependencies>

 <build>
        <resources>
            <!-- src/main/resources目录下的所有文件 -->
            <resource>
                <directory>src/main/resources</directory>
            </resource>

            <!-- src/main/java目录下的xml文件,也就是我们需要的 XxxMapper.xml 映射文件 -->
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>


</project>

2. Create database table

create table `mybatis_monster_` (
	`monster_id` int  	primary key  auto_increment,
	`age` mediumint unsigned not null default 0,
	`birthday` date not null,
	`email` varchar(255) not null default '[email protected]',
	`gender` TINYINT unsigned not null default 1,
	`name` varchar(255) not null default '',
	`salary` double not null default 0.0
	)charset=utf8 engine=InnoDB;

3. Configure a log output file of log4j.xml

Just pay attention to using this log4j template (the template comes from the Internet, log4j2 is a new version, log4j has stopped maintaining, and I don’t understand log4j yet, so I won’t delve into it yet), there is no need to remember it.

It will be modified in the future. Don’t worry too much. I tell you to use it this way and you can use it this way.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd">
<log4j:configuration>
<!--    使用 ConsoleAppender 来输出日志,到IDE的控制台-->
    <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<!--        输出的编码是utf-8 -->
        <param name="Encoding" value="UTF-8"/>
<!--        输入日志的布局格式-->
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n"/>
        </layout>
    </appender>
<!--   日志记录 java.sql包下的类产生的debug级别的错误信息 -->
    <logger name="java.sql">
        <level value="debug"/>
    </logger>
<!--    日志记录 org.apache.ibatis产生的debug级别的错误信息-->
    <logger name="org.apache.ibatis">
        <level value="debug"/>
    </logger>
    <root>
        <level value="debug"/>
        <appender-ref ref="STDOUT"/>
    </root>


</log4j:configuration>

4. Configure myBatis-config.xml

mybatis official website mybatis – MyBatis 3 | Configuration icon-default.png?t=N7T8https://mybatis.org/mybatis-3/zh_CN/configuration.html

Copy the header of the xml file from the official website document and modify it. (Note that there may be errors in copying and pasting, such as extra spaces and periods, which will cause failure to read the configuration file)

<?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">
<!--        配置我们myBatis的环境-->
        <environment id="development">
<!--            mybatis使用事务管理器是jdbc直连方式-->
            <transactionManager type="JDBC"/>
<!--            配置我们的数据源-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatisdb"/>
                <property name="username" value="root"/>
                <property name="password" value=""/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
<!--        这里引入或者说注册我们的MonsterMapper.xml文件-->
<!--        <mapper resource="com/bin/mybatis/mapper/MonsterMapper.xml"/>-->
        <package name="com.bin.mybatis.mapper"/>
    </mappers>
</configuration>

5. Write javaBean: Monster

//This is an ordinary Pojo class
//Because the query results using the original sql statement still need to be encapsulated into objects
//So the entity class attribute names here are consistent with the database table field names
// (must be followed, otherwise the processing will be messed up ,
// Of course there are ways to handle it)

package com.bin.mybatis.entity;

import java.util.Date;

//这就是一个普通的Pojo类
//因为使用原生态的sql语句查询结果还是要封装成对象
//所以这里的实体类属性名和数据库表字段名一致
// (必须遵守,否则处理会踩坑,
// 当然也有方法可以处理)
public class Monster {
    private Integer monster_id;
    private Integer age;
    private Date  birthday;
    private String  email;
    private Integer gender;
    private String  name;
    private Double salary;

    public Monster(Integer monster_id, Integer age, Date birthday, String email, Integer gender, String name, Double salary) {
        this.monster_id = monster_id;
        this.age = age;
        this.birthday = birthday;
        this.email = email;
        this.gender = gender;
        this.name = name;
        this.salary = salary;
    }

    public Monster() {
    }

    public Integer getMonster_id() {
        return monster_id;
    }

    public void setMonster_id(Integer monster_id) {
        this.monster_id = monster_id;
    }

    public Integer getAge() {
        return age;
    }

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

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getGender() {
        return gender;
    }

    public void setGender(Integer gender) {
        this.gender = gender;
    }

    public String getName() {
        return name;
    }

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

    public Double getSalary() {
        return salary;
    }

    public void setSalary(Double salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "Monster{" +
                "monster_id=" + monster_id +
                ", age=" + age +
                ", birthday=" + birthday +
                ", email='" + email + '\'' +
                ", gender=" + gender +
                ", name='" + name + '\'' +
                ", salary=" + salary +
                '}';
    }
}

6. Write the interface MonsterMapper 

The crud method of the entity defined in the interface

package com.bin.mybatis.mapper;

import com.bin.mybatis.entity.Monster;

public interface MonsterMapper {
    //添加方法
    public void addMonster(Monster monster);
}

7. Configure the mapper MonsterMapper.xml

The header is copied from the official website, and the mybatis configuration is given in front of the address.

Pay attention to the comments, there are more details here

Special note: #{x} here represents the attributes of the entity. How to understand: In the insert statement, the front is the database field value, and the back is the attribute value. Since the passed parameters need to be distinguished, there is this #{}

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!-- mapper:表示一个映射器
           1. namespace="com.bin.mybatis.mapper.MonsterMapper"
                  说明本mapper.xml文件是用来映射管理MonsterMapper接口
                 ,主要是去实现MonsterMapper接口声明方法
           2.select:实现一个查询操作 insert:表示一个添加操作
           3.id="addMonster"表示MonsterMapper接口的方法名
           4.resultType="xx"返回的结果类型,如果没有就不需要写
           5.parameterType="com.itbul1.mybatis.entity.Monster"表示该方法输入的参数类型
-->
<mapper namespace="com.bin.mybatis.mapper.MonsterMapper">
    <insert id="addMonster" parameterType="com.bin.mybatis.entity.Monster">
        INSERT INTO mybatis_monster_ (monster_id,age,birthday,email,gender,name,salary)
        VALUES (#{monster_id},#{age},#{birthday},#{email},#{gender},#{name},#{salary})
    </insert>
</mapper>

8. Use junit testing

Pay attention to testing methods

// Get myBatis-config.xml and convert it into an inputStream

  //Get a reply through the sqlSessionFactory object

 //Get the monsterMapper interface object through session

package com.bin.mybatis.test;

import com.bin.mybatis.entity.Monster;
import com.bin.mybatis.mapper.MonsterMapper;
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.InputStream;
import java.util.Date;

public class testMybatis {
    private SqlSessionFactory sqlSessionFactory;
    private SqlSession session;
    private MonsterMapper monsterMapper;
    @Before
    public void init() throws Exception{
//        得到myBatis-config.xml,转换成一个inputStream
        InputStream inputStream = Resources.getResourceAsStream("myBatis-config.xml");
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //通过sqlSessionFactory对象获取一个回话
        session = sqlSessionFactory.openSession();
        //通过session获取到 monsterMapper这个接口对象
       monsterMapper = session.getMapper(MonsterMapper.class);

    }
    @Test
    public void test01() {
        Monster monster = new Monster();

        monster.setAge(100);
        monster.setBirthday(new Date());
        monster.setEmail("[email protected]");
        monster.setGender(1);
        monster.setSalary(8928.00);
        monster.setName("银角");

        monsterMapper.addMonster(monster);

    }
    @After
    public void destory() throws Exception{
        if (session != null) {
            session.commit();
            session.close();
        }
    }
}

9. Successfully added a piece of data

 

Detailed description (error report):

                In this case, several exceptions were encountered

                1. Unable to read the mybatis configuration file. Reason: I didn’t pay attention to checking when copying and pasting the table header, and there were extra dots.

                2. Unable to open session, null pointer exception. Reason: Changed the label of the configuration mapping file and scanned the entire package instead.

                3. The mapping file cannot be found. The reason has been stated at the beginning. The xml file under src will not be output to the target/classes directory during construction , so it cannot be found.

おすすめ

転載: blog.csdn.net/qq_36684207/article/details/135118510