MyBatis: the first program

Table of contents

What is MyBatis

Persistence

Why do you need Mybatis

Write the first program of MyBatis

1. Build an experimental database

2. Import MyBatis related jar packages

3. Write MyBatis core configuration file

4. Write MyBatis tool class

5. Create an entity class

6. Write Mapper interface class

7. Write Mapper.xml configuration file

8. Write test classes

9. Run the test

10. Description of the problem


What is MyBatis

  • MyBatis is an excellent persistence layer framework

  • MyBatis avoids almost all JDBC code and the process of manually setting parameters and obtaining result sets

  • MyBatis can use simple XML or annotations to configure and map native information, and map interfaces and Java entity classes [Plain Old Java Objects, ordinary Java objects] into records in the database.

  • MyBatis was originally an open source project of apache, ibatis. In 2010, this project was migrated from apache to google code and renamed MyBatis.

  • Migrated to Github in November 2013 .

  • Mybatis official document: http://www.mybatis.org/mybatis-3/zh/index.html

  • GitHub :https://github.com/mybatis/mybatis-3

Persistence

  • The code block that completes the persistence work. ----> dao layer [DAO (Data Access Object) data access object]

  • In most cases, especially for enterprise-level applications, data persistence often means saving the data in memory to disk for curing, and the implementation process of persistence is mostly completed through various relational databases .

  • However, there is one word here that needs special emphasis, which is the so-called "layer". For application systems, data persistence is mostly an essential component. In other words, our system already has the concept of "persistence layer" naturally? Maybe, but maybe that's not the case. The reason why the concept of a "persistence layer" is independent instead of "persistence module" and "persistence unit" means that in our system architecture, there should be a relatively independent logical level that focuses on data persistence implementation of logic.

  • Compared with other parts of the system, this level should have a clearer and stricter logical boundary. [To put it bluntly, it is used to operate the database!

Why do you need Mybatis

  • Mybatis is to help programmers store data in the database and retrieve data from the database.

  • In traditional jdbc operations, there are many repetitive code blocks. For example: encapsulation when data is fetched, database connection establishment, etc., through the framework, repeated code can be reduced and development efficiency can be improved.

  • MyBatis is a semi-automatic ORM framework (Object Relationship Mapping) --> Object Relationship Mapping

  • All things can still be done without Mybatis, but with it, all implementations will be easier! There is no distinction between high and low technology, only the people who use this technology are high or low

  • Advantages of MyBatis

    • Easy to learn: itself is small and simple. There is no third-party dependency. The simplest installation only needs two jar files and several sql mapping files. It is easy to learn and use. Through the documentation and source code, you can fully grasp its design ideas and implementation.

    • Flexible: mybatis does not impose any impact on the existing design of the application or database. SQL is written in xml, which is convenient for unified management and optimization. All requirements for operating the database can be met through sql statements.

    • Uncoupling sql and program code: By providing a DAO layer, business logic and data access logic are separated, making the system design clearer, easier to maintain, and easier to unit test. The separation of sql and code improves maintainability.

    • Provide xml tags and support writing dynamic sql.

    • .......

  • Most importantly, many people use it! The company needs it!

Write the first program of MyBatis

Idea flow: build environment --> import Mybatis ---> write code ---> test

code demo

1. Build an experimental database

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,'狂神','123456'),(2,'张三','abcdef'),(3,'李四','987654');

2. Import MyBatis related jar packages

  • Find on GitHub

<dependency>
   <groupId>org.mybatis</groupId>
   <artifactId>mybatis</artifactId>
   <version>3.5.2</version>
</dependency>
<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.47</version>
</dependency>

3. Write MyBatis core configuration file

  • View help documentation

<?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"/>
           <dataSource type="POOLED">
               <property name="driver" value="com.mysql.jdbc.Driver"/>
               <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf8"/>
               <property name="username" value="root"/>
               <property name="password" value="123456"/>
           </dataSource>
       </environment>
   </environments>
   <mappers>
       <mapper resource="com/kuang/dao/userMapper.xml"/>
   </mappers>
</configuration>

4. Write MyBatis tool class

  • View help documentation

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 java.io.IOException;
import java.io.InputStream;

public class MybatisUtils {

   private static SqlSessionFactory sqlSessionFactory;

   static {
       try {
           String resource = "mybatis-config.xml";
           InputStream inputStream = Resources.getResourceAsStream(resource);
           sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
      } catch (IOException e) {
           e.printStackTrace();
      }
  }

   //获取SqlSession连接
   public static SqlSession getSession(){
       return sqlSessionFactory.openSession();
  }

}

5. Create an entity class

public class User {
   
   private int id;  //id
   private String name;   //姓名
   private String pwd;   //密码
   
   //构造,有参,无参
   //set/get
   //toString()
   
}

6. Write Mapper interface class

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

public interface UserMapper {
   List<User> selectUser();
}

7. Write Mapper.xml configuration file

  • namespace is very important, you can't write it wrong!

<?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.kuang.dao.UserMapper">
 <select id="selectUser" resultType="com.kuang.pojo.User">
  select * from user
 </select>
</mapper>

8. Write test classes

  • Junit package test

public class MyTest {
   @Test
   public void selectUser() {
       SqlSession session = MybatisUtils.getSession();
       //方法一:
       //List<User> users = session.selectList("com.kuang.mapper.UserMapper.selectUser");
       //方法二:
       UserMapper mapper = session.getMapper(UserMapper.class);
       List<User> users = mapper.selectUser();

       for (User user: users){
           System.out.println(user);
      }
       session.close();
  }
}

9. Run the test

Our data has been successfully queried, ok!

10. Description of the problem

Description of possible problems: Maven static resource filtering problem

<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>

Guess you like

Origin blog.csdn.net/weixin_45987577/article/details/126636284