Learn about MyBatis ~ basic introduction to MyBatis and basic use of MyBatis


1, Basic introduction to MyBatis framework:

1. Meet MyBatis:

  • MyBatis is a persistence layer framework that supports ordinary SQL queries, stored procedures and advanced mapping. Strictly speaking, it should be an SQL mapping framework.

  • Its predecessor is iBatis, the persistence layer framework used by Taobao.

  • Almost all the manual setting of JDBC code and parameters and the processing of result set can be completed by MyBatis, which can be completed by simply using XML or annotation configuration.

  • Compared with Hibernate, it is simpler, lower level and better performance, so it is more popular and favored by enterprises.


2. Download address and documentation:

​                        http://mybatis.org/spring/zh/index.html



2, MyBatis basic use

1. Development step 1: copy jar package

■ when copying jar of the project, remember to create a lib directory first

  • mysql connection driver jar package [jdbc at the bottom of MyBatis]
  • myBatis.jar

2. Development step 2: write configuration file [main configuration file and mapping file]

2-1. Learn about the configuration files of MyBatis (two types - main configuration file and mapping file):

(1) MyBatis global profile / master profile:
  • Naming: not fixed, but you need to see the meaning of the name, for example: mybatis config xml
  • Path: the root path of the classpath
  • Reference document: xml configuration chapter of mybatis Chinese official website
✿ MyBatis global configuration file content:

① Global configuration information

② Attribute configuration information

③ Plug in configuration information

④ Configure environment information [transaction + connection pool]

⑤ Association mapping file


(2) MyBatis mapping file / Mapper file:
  • For example, xmapper needs a fixed name XML, which object is the mapping file, such as usermapper xml
  • Path: the Mapper file should be placed in the path of the Mapper interface, but temporarily in the domain
  • Reference document: Chapter of xml Mapping file of mybatis Chinese official website
✿ MyBatis mapping file content:

① Write the addition, deletion, modification and query sql, and store the sql in the insert| update| delete| select element

② Result set mapping: solve the problem of mismatch between columns and object attributes in the table

③ Cache configuration


2-2. Constraint file of configuration file [constraint file is in the introduction chapter]:

//Constraint file of mybatis main configuration file [for example, mybatis-config.xml] - mybatis-3-config.xml DTD [online status, it will download automatically]
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">

 //Constraint file of mybatis mapping file [such as UserMapper.xml] - mybatis mapper DTD [online status, it will download automatically]
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

■ associate local files to prevent download failure due to poor network


2-3. Write the contents of main configuration file and mapping file

✿ global / main configuration file [mybatis config. XML file]:
  • Configure environment information [transaction + connection pool]
  • Association mapping file
  <configuration>
  	<environments default="dev">
	  <!-- Development environment: in the future, the transaction manager and link pool are handed over to spring Framework to manage -->
	  	<!-- 1,Configure the environment of the database -->
	  	<environment id="dev">
	  		<!-- ① Transaction manager -->
	  		<transactionManager type="JDBC"/>
	  		<!-- ② Connection pool [connection database 4 elements] -->
	  		<dataSource type="POOLED">
	  			<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
	  			<property name="url" value="jdbc:mysql://localhost:3306/mybatisdemo"/>
	  			<property name="username" value="root"/>
	  			<property name="password" value="admin"/>
	  		</dataSource>
	  	</environment>
  </environments>
  	<!-- 2,Association mapping file  -->
	<mappers>
	<!-- The global configuration file is in the project output path bin Under the directory -->
	<!-- classpath Path (the default project output path is bin[Compile into class Bytecode folder bin,Before compilation, it is in the source code src]) -->
		<mapper resource="com/shan/hello/UserMapper.xml"/>
	</mappers>
  </configuration>



✿ mapping file [UserMapper.xml file]:
  • Write sql for adding, deleting, modifying and querying
  <!-- namespace Namespace: corresponding Mapper The fully qualified name of the interface, i.e. write the fully qualified name of the class temporarily
  		different mappe Document namespace It's different.
  		mapper of namespace combination id Attributes[ namespace.id]It uniquely represents a certain item in the application sql sentence.
   -->
  <mapper namespace="com.shan.hello.UserMapper">
  	  <!-- select Tags: used to write queries sql sentence
  	  	id: A unique identifier that identifies the referenced item sql sentence
		parameterType:Indicates the execution of the sql The parameter types required by the statement are not recommended, MyBatis It can be inferred
		resultType:What kind of objects are encapsulated into each row of data in the result set
  	   -->
	  <select id="get" parameterType="java.lang.Long" resultType="com.shan.hello.User">
	    select * from t_user where id = #{id}
	  </select>
</mapper>

3. Development step 3: write test code, test myBatis, and perform addition, deletion, modification and query operations:

  • Take query as an example:

    ① Load profile

    ② Create a session factory object SqlSessionFactory [like connection pool DataSource]

    ③ Create the session object SqlSession through the session factory [like the Connection object Connection]

    ④ Perform crud operation

    ⑤ Close resource

	public void testGet() throws IOException {
		//1. Load the mybatis global configuration file mybatis config. From the classpath path xml
		InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
		//2. Create a sqlsessonfactory session factory object, such as a connection pool DataSource
		SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
		//3. Create a SqlSession session object, such as the Connection object Connection
		SqlSession session = factory.openSession();
		//4. Perform database operations (CRUD)
		User user = session.selectOne("com.shan.hello.UserMapper.get", 300L);
    	System.out.println(user);
		//5. Close resource
		session.close();
	}

❀ summary: development process - copy the jar package, write the configuration file, and then test

Added by FUNKAM35 on Mon, 31 Jan 2022 10:25:34 +0200