MyBatis (a) introductory overview and environmental structures

1. Framework Overview

1.1 What is the framework

  • What is frame
    frame (Framework) is designed entirely or partially reusable system, the performance of a set of methods and between the member instance of an abstract interaction member; another definition that, the framework may be customized application developer application skeleton. The former is defined from the application of the latter is given from the aspect of the purpose.
  • Framework to solve the problems
    of the most important problem to be solved is the framework for the integration of technical problems. Usually the frame in an intermediate layer between the low-level application platforms (such as J2EE), and high-level business logic. The importance of the framework is that it implements some functions, and can be a very good low-level and high-level business logic application platform has been eased.

1.2MyBatis Framework Overview

  • Basic Information
  • mybatis is an excellent java-based persistence framework, which encapsulates the internal jdbc, so developers only need to focus sql statement itself, without the need to spend energy to handle the loading drive, create a connection, create complicated process statement and so on.
  • mybatis xml or annotation by way of various configuration statement to be executed together, and the final map generation sql statement executed by a java objects and dynamic parameters of the sql statement, and finally execute sql and mapping the result to the frame by a java object and mybatis return.
  • Using ORM idea to solve the problem of database entities and mapping of jdbc is encapsulated, shielded jdbc api-level access details, so that we do not have to deal with jdbc api, you can complete the operation of the database persistence.
  • MyBatis functional architecture:
  1. API interface layer: API provides an interface to external use, by the developer to manipulate these local database API. An interface layer receiving the call request will call the data processing layer to accomplish their data processing.
  2. Data processing layer: responsible for specific SQL lookup, SQL parsing, SQL execution and implementation of the results of the mapping process and so on. Its main purpose is to complete the operation at the request of a database call.
  3. Base support layer: responsible for the most basic functions of support, including connection management, transaction management, load and configure caching, these are common things that will draw them out as the most basic components. Most basic support for the upper layer data processing.
  • MyBatis advantages and disadvantages
  • Advantages:
    easy to learn, flexible
    lifting sql coupled with the program code
    to provide xml tags, support the development of dynamic sql
  • Disadvantages:
  • When writing SQL statements heavy workload, especially in the field more, the association table for a long time, especially
    SQL statement depends on the database, resulting in poor portability database

2. Getting Started

2.1 Development Readiness

  • Create a database and user table, then insert the data, SQL statement is as follows:
CREATE DATABASE eesy;

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(32) NOT NULL COMMENT '用户名称',
  `birthday` datetime DEFAULT NULL COMMENT '生日',
  `sex` char(1) DEFAULT NULL COMMENT '性别',
  `address` varchar(256) DEFAULT NULL COMMENT '地址',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;


INSERT INTO `user` VALUES ('1', '李一', '2020-02-01 17:47:08', '男', '北京');
INSERT INTO `user` VALUES ('2', '刘二', '2020-02-02 15:09:37', '女', '上海');
INSERT INTO `user` VALUES ('3', '张三', '2020-03-03 11:34:34', '女', '广东');
INSERT INTO `user` VALUES ('4', '赵四', '2020-03-04 12:04:06', '男', '杭州');
INSERT INTO `user` VALUES ('5', '王五', '2020-03-05 17:37:26', '男', '深圳');

  • Download mybatis mybatis development package from the official website (here I use Sakamoto is 3.4.5)
  • Create a maven project, project called mybatis_01, project information as follows :
    1, click on Create New Project to create a project
    Here Insert Picture Description2, click the Next
    Here Insert Picture Description3, fill in the project GroupId and ArtifactId, click Next Here Insert Picture Description
    4. The following is the directory structure of the project
    Here Insert Picture Description
  • Mybatis3.4.5 added in pom.xml file coordinates, as follows:
    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

2.2 User entity class

  • Write a user entity class
public class User implements Serializable{

    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;

    public Integer getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Date getBirthday() {
        return birthday;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", birthday=" + birthday +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

2.3 持久层接口IUserDao

创建接口IUserDao,为了演示此处只定义一个查询所有的方法

public interface IUserDao {

    /**
     * 查询所有
     * @return
     */
    List<User> findAll();
}

2.4 持久层接口的映射文件IUserDao.xml

要求:创建位置必须和持久层接口在相同的包中
           必须以持久层接口名称命名文件名,扩展名是.xml
完整代码如下:

<?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.wink.dao.IUserDao">
    <!-- 配置查询所有-->
    <select id="findAll" resultType="com.wink.domain.User">
        select * from user
    </select>
</mapper>

2.5 SqlMapConfig.xml配置文件

下面通过xml配置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">
<!-- mybatis的主配置文件-->
<configuration>
    <!-- 配置环境-->
    <environments default="mysql">
        <!-- 配置mysql的环境-->
        <environment id="mysql">
            <!-- 配置事务的类型-->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 配置数据源(连接池)-->
            <dataSource type="POOLED">
                <!-- 配置连接数据库的基本信息-->
                <property name="driver" value="com.mysql.jdbc.Driver"></property>
                <property name="url" value="jdbc:mysql:///eesy"></property>
                <property name="username" value="root"></property>
                <property name="password" value="root"></property>
            </dataSource>
        </environment>
    </environments>

    <!-- 指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件-->
    <mappers>
        <mapper resource="com/wink/dao/IUserDao.xml"></mapper>
    </mappers>
</configuration>

2.6 进行测试

编写一个Mybatis的测试类,测试上述查询所有的方法,这里直接使用main方法测试:
第一步:读取配置文件
第二步:创建SqlSessionFactory工厂
第三步:创建SqlSession
第四步:创建Dao接口的代理对象
第五步:执行dao中的方法
第六步:释放资源

public class MybatisTest {

    /**
     * 入门案例
     * @param args
     */
    public static void main(String[] args)throws Exception {
        //1.读取配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        //3.使用工厂生产SqlSession对象
        SqlSession session = factory.openSession();
        //4.使用SqlSession创建Dao接口的代理对象
        IUserDao userDao = session.getMapper(IUserDao.class);
        //5.使用代理对象执行方法
        List<User> users = userDao.findAll();
        for(User user : users){
            System.out.println(user);
        }
        //6.释放资源
        session.close();
        in.close();
    }
}

下面执行MybatisTest,可以看到成功运行
Here Insert Picture Description

3.补充(基于注解的mybatis使用)

  • mybatis基于注解的入门案例
    把IUserDao.xml移除,在dao接口的方法上使用@Select注解,并且指定SQL语句。同时需要在SqlMapConfig.xml中的mapper配置时,使用class属性指定dao接口的全限定类名

3.1 在持久层接口中添加注解

public interface IUserDao {
    /**
     * 查询所有操作
     * @return
     */
    @Select("select * from user")
    List<User> findAll();
}

3.2 修改SqlMapConfig.xml

<!-- 告知 mybatis 映射配置的位置 --> 
<mappers> 
   <mapper class="com.itheima.dao.IUserDao"/>
</mappers> 

注意:在使用基于注解的 Mybatis 配置时,需要移除 xml 的映射配置(IUserDao.xml)

4.注意事项

  • When setting up the environment :
    1. Create IUserDao.xml and IUserDao.java time and name to be consistent with our previous knowledge. In Mybatis in its name and the operator interface mapping file persistence layer is also called: Mapper. Therefore: IUserDao same and IUserMapper
    2, the position of the mapping profile and packet structure must mybatis dao same interface
    3, the value mapper mapping configuration file namespace attribute tag must be fully qualified class name dao interface
  • In the test code :
    Do not forget to inform mybatis to be encapsulated in the map configuration to which entity classes
    are arranged: Specify the fully qualified class name of the entity class
Released nine original articles · won praise 1 · views 276

Guess you like

Origin blog.csdn.net/qq_41460383/article/details/104398524