MyBatis (a) --- realization MyBatis program

A, MyBatis Introduction

MyBatis is a common SQL query support, excellent persistence framework stored procedures and advanced mappings. MyBatis eliminates almost all of the code and to manually set parameters JDBC package and retrieve the result set. MyBatis can use simple XML or Annotations for configuration and map primitives, Map interfaces and Java POJO (Plain Old Java Objects, ordinary Java Objects) to database records in

Two, MyBatis advantage

Did not have to write complex code that JDBC

  • Easy to learn, do not rely on third-party program or framework.
  • Official website documentation powerful, open source, we can always analyze source code ';
  • Decoupling, low coupling, high cohesion
  • ORM; object-relational mapping
  • Provide XML tags;

Three, Mybatis program

1, set up the experimental environment, create a database

1-1, MySQL Code

CREATE DATABASE `mybatis` ;

USE `mybatis`;

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
  `id` INT(20) NOT NULL,
  `name` VARCHAR(30) DEFAULT NULL,
  `pwd` VARCHAR(30) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;

INSERT  INTO `user`(`id`,`name`,`pwd`) 
VALUES (1,'闪电侠','123'),(2,'蜘蛛侠','abc'),(3,'钢铁侠','520');

1-2, the results
Here Insert Picture Description

2, create a common Maven project

2-1, create Maven
Here Insert Picture Description
Here Insert Picture Description
2-2, write 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.Shandx</groupId>
    <artifactId>ssm-mybatis-study</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!--单元测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>

        <!--mybatis的包-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.1</version>
        </dependency>

        <!--连接数据库的驱动包-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
    </dependencies>

    <build>
        <!--希望maven在导出项目的时候,能够将我们的配置及资源导出-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

</project>

3, write code

3-1, create entity classes pojo

public class User {

    private int id;
    private String name;
    private String pwd;

    public User() {
    }

    public User(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }

    public int getId() {
        return id;
    }

    public void setId(int 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 password) {
        this.pwd = password;
    }

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

3-2, built a mybatis-config.xml in resources, write mybatis profile
Here Insert Picture Description

<?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>
    <!--配置环境,这里可以有多套环境 default代表默认的是那一套-->
    <environments default="development">
        <!--配置一套环境 id .环境的名字-->
        <environment id="development">
            <!--transactionManager:事务管理,type:jdbc-->
            <transactionManager type="JDBC"/>
            <!--dataSource 数据源-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <!--xml中不允许&符号直接出现,我们需要使用 &amp; 代替-->
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;charsetEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
</configuration>

3-3, creation tools

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;

//mybatis的工具类,重复的代码的提纯
public class MyBatisUtils {

    //类变量不需要设置默认值;
    private static SqlSessionFactory sqlSessionFactory;

    static {
        //在maven中,所有的资源文件一般都放在resources目录下,我们可以直接拿到。
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //设置SqlSessionFactory公共的方法
    public static SqlSessionFactory getSqlSessionFactory(){
        return sqlSessionFactory;
    }
}

3-4, the mapping file interface

import com.shandx.pojo.User;
import java.util.List;

public interface UserMapper {

    //获取全部的用户
    List<User> selectUser();

}

3-5, the preparation of the corresponding mapper mapping file

<?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接口的类-->
<mapper namespace="com.Shandx.dao.UserMapper">
    <!--select标签的id对应映射接口的方法名字  resultType:返回结果的类型  中间就编写sql语句-->
    <select id="selectUser" resultType="com.Shandx.pojo.User">
        select * from user
    </select>

</mapper>

3-6, the binding written mapping file mybatis profile

<?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>
    <!--配置环境,这里可以有多套环境 default代表默认的是那一套-->
    <environments default="development">
        <!--配置一套环境 id .环境的名字-->
        <environment id="development">
            <!--transactionManager:事务管理,type:jdbc-->
            <transactionManager type="JDBC"/>
            <!--dataSource 数据源-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <!--xml中不允许&符号直接出现,我们需要使用 &amp; 代替-->
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;charsetEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>

    <!--关联映射文件-->
    <mappers>
        <mapper resource="com/kuang/dao/userMapper.xml"/>
    </mappers>

</configuration>

4, test

Write the corresponding test class in maven test folder

import com.Shandx.dao.UserMapper;
import com.Shandx.pojo.User;
import com.Shandx.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;

import java.util.List;

public class UserMapperTest {
    @Test
    public void selectUser(){

        //1.拿到sqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = MyBatisUtils.getSqlSessionFactory();
        //2.通过sqlSessionFactory对象openSession()创建一个sqlSession。
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3.通过sqlSession获得mapper对象 , 参数为映射文件对应的接口类的class对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //4.通过mapper对象来执行操作;
        List<User> users = mapper.selectUser();

        //获得结果集
        for (User user : users) {
            System.out.println(user);
        }
        
    }
}

5, results show

Here Insert Picture Description

Fourth, the project structure

Here Insert Picture Description

Guess you like

Origin www.cnblogs.com/tqsh/p/11310466.html