[Mybatis series] How to use Mybatis

Preface: Before summarizing this blog, I have already used mybatis, but mybatis is just a simple use, so why don't we use JDBC? And want to use Mybatis? Let’s introduce it below

Problems with JDBC:

  1. Frequent database connection creation and release cause waste of system resources and affect system performance. If you use a database connection pool, you can solve this problem.
  2. Sql statements are hard-coded in the code, which makes the code difficult to maintain. The actual application of sql may change greatly. SQL changes require changing the java code.
  3. Using preparedStatement to pass parameters to placeholders is hard-coded, because the where condition of the SQL statement is not necessarily, and it may be more or less. Modifying the SQL requires modifying the code, and the system is not easy to maintain.
  4. There is hard coding for the result set analysis (query column name), sql changes lead to changes in the analysis code, the system is not easy to maintain, if the database records can be encapsulated into pojo object analysis is more convenient

What is Mybatis:

    mybatis is a persistence layer framework that avoids almost all JDBC code and the process of manually setting parameters

What is persistence?

    Save data (that is, objects in memory) to a storage device that can be stored permanently,

Why do we need persistence service?

    Data will be lost after the memory is powered off, but some objects will not be lost anyway, the memory is too expensive compared to the hard disk

Below we use a simple example to introduce the use of mybatis

First create a Maven project:

  • Import dependencies:
<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>
  • Write the core configuration file of 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">
<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&useUnicode=true&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>

Environments means multiple environments. A configuration file can have multiple environments, such as testing, development, and production. Each environment has its own id

default means the default environment

  • Create an entity class:
public class User {  
   private int id;  //id
   private String name;   //姓名
   private String pwd;   //密码
   
   //构造,有参,无参
   //set/get
   //toString()
}
  • Write Mapper interface:
import com.kuang.pojo.User;
import java.util.List;
public interface UserMapper {
   List<User> selectUser();
}
  • Write the Mapper.xml configuration 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="com.kuang.dao.UserMapper">
 <select id="selectUser" resultType="com.kuang.pojo.User">
  select * from user
 </select>
</mapper>
  • Finally load the main configuration file:
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();
  }
}

        sqlSessionFactoryBuilder creates sqlSessionFactory

        sqlSessionFactory creates sqlSession

         Here, SqlSessionFactoryBuilder is used to create SqlSessionFacoty. Once SqlSessionFacoty is created, SqlSessionFactoryBuilder is not needed. Because SqlSession is produced by SqlSessionFactory, SqlSessionFactoryBuilder can be used as a tool class. The best use range is method scope, that is, local variables in the method body.

        SqlSessionFactory is an interface. Different overloading methods of openSession are defined in the interface. The best use range of SqlSessionFactory is during the entire application runtime. Once created, it can be reused. SqlSessionFactory is usually managed in a singleton mode.

  • Create MybatisUtils
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();
      }
  }
 

 

Guess you like

Origin blog.csdn.net/qq_30631063/article/details/108200369