Introduction to MyBatis and the first program

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] to records in the database.

MyBatis was originally an open source project ibatis of apache. In 2010, this project was migrated from apache to google code, and was 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

Why do you need Mybatis

Simplifying operation
Mybatis is to help programmers store data in the database and fetch data from the database.

Traditional jdbc operations have many duplicate code blocks. For example: encapsulation when data is retrieved, database connection establishment, etc..., the framework can reduce duplication of code and improve development efficiency.

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

All things can be done without Mybatis, but with it, all implementations will be easier! There is no high or low technology, only the people who use this technology have high or low differences

Advantages of MyBatis

Simple and easy to learn. In
itself, it is small and simple. There is no third-party dependency. The simplest installation is as long as two jar files + a few sql mapping files are configured. It is easy to learn and easy to use. Through the documentation and source code, you can fully grasp its design ideas and implementation.

The flexible
mybatis does not impose any influence on the existing design of the application or database. sql is written in xml, which is convenient for unified management and optimization. Through the sql statement can meet all the needs of operating the database.

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, support writing dynamic sql.

The first MyBatis program

Idea process: 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 the MyBatis related jar package

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 the core configuration file of MyBatis

View the help document

<?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 the help document

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 the Mapper.xml configuration file

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

There may be a problem

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/david2000999/article/details/114526798