Mybatis quick start

Posted by Quicksilver_0 on Fri, 04 Mar 2022 03:49:02 +0100

1. Introduction to mybatis

1.1 original jdbc operation (query data)

1.2 original jdbc operation (insert data)

1.3 analysis of original jdbc operation

The problems existing in the original jdbc development are as follows:

① The frequent creation and release of database connections cause a waste of system resources, which affects the system performance

② 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 need to change the java code.

③ When querying, you need to manually encapsulate the data in the result set into the entity. When inserting, you need to manually set the data of the entity to the placeholder position of the sql statement

Solutions to the above problems:

① Initialize connection resources using database connection pool

② Extract sql statements into xml configuration file

③ Use reflection, introspection and other underlying technologies to automatically map attributes and fields between entities and tables

1.4 what is Mybatis

mybatis is an excellent persistence layer framework based on java. It encapsulates jdbc internally, so that developers only need to pay attention to the sql statement itself, and do not need to spend energy to deal with the complicated processes such as loading driver, creating connection, creating statement and so on.

mybatis configures various statements to be executed by means of xml or annotation, and generates the final executed sql statement by mapping java objects with the dynamic parameters of sql in the statement.

Finally, the mybatis framework executes sql and maps the results to java objects and returns them. The ORM idea is adopted to solve the problem of entity and database mapping, encapsulate jdbc and shield the underlying access details of jdbc api, so that we can complete the persistence operation of database without dealing with jdbc api.

2. Quick start to mybatis

2.1 MyBatis development steps

MyBatis official website address: http://www.mybatis.org/mybatis-3/

MyBatis development steps:

① Add coordinates for MyBatis

② user table creation

③ Write User entity class

④ Write the mapping file usermapper xml

⑤ Write the core file sqlmapconfig xml

⑥ Write test class

2.2 environment construction

1) Import the coordinates of MyBatis and other related coordinates

<!--mybatis coordinate-->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.5</version>
</dependency>
<!--mysql Driving coordinates-->
<dependency>    
    <groupId>mysql</groupId>   
    <artifactId>mysql-connector-java</artifactId>    
    <version>8.0.28</version>    
    <scope>runtime</scope>
</dependency>
<!--Unit test coordinates-->
<dependency>    
    <groupId>junit</groupId>    
    <artifactId>junit</artifactId>    
    <version>4.12</version>    
    <scope>test</scope>
</dependency>
<!--Log coordinates-->
<dependency>    
    <groupId>log4j</groupId>    
    <artifactId>log4j</artifactId>    
    <version>1.2.12</version>
</dependency>
  1. Create user data table

  1. Write User entity
public class User {    
	private int id;    
	private String username;    
	private String password;
    //Omit the get and set methods
}

4) Write UserMapper mapping file resources / COM / Cheung / mapper / UserMapper 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="userMapper">    
	<select id="findAll" resultType="com.itheima.domain.User">        
		select * from User    
	</select>
</mapper>
  1. Write MyBatis core file resources / sqlmapconfig xml
<!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:///test"/>                
				<property name="username" value="root"/>
				<property name="password" value="root"/>            
			</dataSource>        
		</environment>    
	</environments>    
	
	<mappers> 
		<mapper resource="com/itheima/mapper/UserMapper.xml"/> 
	</mappers>
</configuration>

2.3 writing test code

//Loading the core configuration file resources is provided by the mybatis package (import org.apache.ibatis.io.Resources;)
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
//Get sqlSession factory object
SqlSessionFactory sqlSessionFactory = new            
                           SqlSessionFactoryBuilder().build(resourceAsStream);
//Get sqlSession object
SqlSession sqlSession = sqlSessionFactory.openSession();
//Execute sql statement namespace+id in mapper file
List<User> userList = sqlSession.selectList("userMapper.findAll");
//Print results
System.out.println(userList);
//Release resources
sqlSession.close();

2.4 knowledge summary

MyBatis development steps:

① Add coordinates for MyBatis

② Create user data table

③ Write User entity class

④ Write the mapping file usermapper xml

⑤ Write the core file sqlmapconfig xml

⑥ Write test class

3. Overview of mybatis mapping file

4. Addition, deletion, modification and query of mybatis

4.1 insert data operation of mybatis

1) Write UserMapper mapping file

<mapper namespace="userMapper">    
	<insert id="add" parameterType="com.itheima.domain.User">        
		insert into user values(#{id},#{username},#{password})    
	</insert>
</mapper>

2) Write code to insert the User entity

@Test //insert
    public void test2() throws IOException {

        //Simulate the data transmitted from the web layer to create a User
        User user = new User();
        user.setUsername("wangwu");
        user.setPassword("456");

        //Load core profile
        InputStream resource = Resources.getResourceAsStream("sqlMapConfig.xml");
        //Get sqlSession factory object
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resource);
        //Obtained sqlSession object
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //Execute sql statement to insert data
        int insert = sqlSession.insert("userMapper.save", user);
        System.out.println(insert);

        //Commit transaction
        sqlSession.commit();
        //Release resources
        sqlSession.close();
    }

3) Precautions for insertion operation

• insert statements use the insert tag

• use the parameterType attribute in the mapping file to specify the type of data to insert

• use #{entity attribute name} in Sql statement to refer to attribute value in entity

• the API used for the insert operation is sqlsession Insert ("namespace. id", entity object);

• the insert operation involves the change of database data, so the commit transaction displayed by the sqlSession object should be used, that is, sqlSession commit()

4.2 data modification of mybatis

1) Write UserMapper mapping file

<mapper namespace="userMapper">
    <update id="update" parameterType="com.itheima.domain.User">
        update user set username=#{username},password=#{password} where id=#{id}
    </update>
</mapper>

2) Write code to modify the User entity

@Test //Update data
    public void test3() throws IOException {

        //Simulate the data transmitted from the web layer to create a User
        User user = new User();
        user.setId(2);
        user.setUsername("zhangxueyou");
        user.setPassword("123");

        //Load core profile
        InputStream resource = Resources.getResourceAsStream("sqlMapConfig.xml");
        //Get sqlSession factory object
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resource);
        //Obtained sqlSession object
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //Execute sql statement to insert data
        int update = sqlSession.update("userMapper.update", user);
        System.out.println(update);
        //Commit transaction
        sqlSession.commit();
        //Release resources
        sqlSession.close();
    }

3) Notes on modification operation

• modify the statement using the update tag

• the API used for modification is sqlsession Update ("namespace. id", entity object);

4.3 data deletion of mybatis

1) Write UserMapper mapping file

<mapper namespace="userMapper">
    <delete id="delete" parameterType="java.lang.Integer">
        delete from user where id=#{id}
    </delete>
</mapper>

2) Write code to delete data

InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
int delete = sqlSession.delete("userMapper.delete",3);
System.out.println(delete);
sqlSession.commit();
sqlSession.close();

3) Precautions for deletion

• delete statements use the delete tag

• use #{arbitrary string} to refer to the single parameter passed in Sql statement

• the API used for deletion is sqlsession Delete ("namespace. id", Object);

4.4 knowledge summary

Add, delete, modify and query mapping and configuration API: 
Query data: List<User> userList = sqlSession.selectList("userMapper.findAll");
    <select id="findAll" resultType="com.itheima.domain.User">
        select * from User
    </select>
Add data: sqlSession.insert("userMapper.add", user);
    <insert id="add" parameterType="com.itheima.domain.User">
        insert into user values(#{id},#{username},#{password})
    </insert>
Modify data: sqlSession.update("userMapper.update", user);
    <update id="update" parameterType="com.itheima.domain.User">
        update user set username=#{username},password=#{password} where id=#{id}
    </update>
Delete data: sqlSession.delete("userMapper.delete",3);
    <delete id="delete" parameterType="java.lang.Integer">
        delete from user where id=#{id}
    </delete>

5. Overview of mybatis core profile

5.1 hierarchical relationship of mybatis core configuration file

5.2 MyBatis common configuration analysis

1)environments tab

The configuration of database environment supports multi environment configuration

There are two types of transaction manager:

• JDBC: this configuration directly uses the commit and rollback settings of JDBC. It relies on the connection from the data source to manage the transaction scope.

• MANAGED: this configuration does little. It never commits or rolls back a connection, but lets the container manage the whole life cycle of the transaction (such as the context of JEE application server). By default, it closes the connection, but some containers don't want this, so you need to set the closeConnection property to false to prevent its default closing behavior.

There are three types of data sources:

• UNPOOLED: the implementation of this data source only opens and closes the connection every time it is requested.

• POOLED: the implementation of this data source uses the concept of "pool" to organize JDBC connection objects.

• JNDI: this data source is implemented to be used in containers such as EJB or application server. The container can configure the data source centrally or externally, and then place a reference to the JNDI context.

2)mapper tag

The function of this tag is to load mapping. The loading methods are as follows (the last three can be understood):

• use resource references relative to Classpaths, for example:

• use fully qualified resource locators (URL s) (rarely used), for example:

• use the mapper interface to implement the fully qualified class name of the class, for example:

• register all mapper interface implementations in the package as mappers, for example:

3)Properties tag

In actual development, it is customary to extract the configuration information of the data source separately into a properties file, which can load additional configured properties files

4)typeAliases label (typed alias)

A type alias is a short name for a Java type. The original type name is configured as follows

Pay attention to the order when configuring typeAliases tags in the mybatis core configuration file, otherwise an error will be reported:

The content of element type "configuration" must match "(properties?,settings?,typeAliases?,typeHandlers?,objectFactory?,objectWrapperFactory?,reflectorFactory?,plugins?,environments?,databaseIdProvider?,mappers?)".

Before alias environment properties

Configure typeAliases as com itheima. domain. User defines the alias as user

The above is our customized alias. The mybatis framework has set up some common types of aliases for us

<!--    Delete operation-->
    <delete id="delete" parameterType="java.lang.Integer">
        delete from user where id=#{id}
    </delete>
<!--    Can be used directly int Replace the same-->
    <delete id="delete" parameterType="int">
        delete from user where id=#{id}
    </delete>
    

5.3 knowledge summary

Common configuration of core profile:

Properties tag: this tag can load external properties files

<properties resource="jdbc.properties"></properties>

typeAliases label: set type aliases

<typeAlias type="com.itheima.domain.User" alias="user"></typeAlias>

mappers tag: load mapping configuration

<mapper resource="com/itheima/mapper/UserMapping.xml"></mapper>

environments tab: data source environment configuration tab

6.MyBatis corresponding API

6.1 SqlSession factory builder

Common API: SqlSessionFactory build(InputStream inputStream)

Build a SqlSessionFactory object by loading the input stream of the core file of mybatis

String resource = "org/mybatis/builder/mybatis-config.xml"; 
InputStream inputStream = Resources.getResourceAsStream(resource); 
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); 
SqlSessionFactory factory = builder.build(inputStream);

Among them, the Resources tool class, which is located at org apache. ibatis. IO package. The Resources class helps you load resource files from a classpath, file system, or a web URL.

6.2 SqlSession factory object SqlSessionFactory

SqlSessionFactory has multiple methods to create SqlSession instances. There are two commonly used:

6.3 SqlSession session object

SqlSession instance is a very powerful class in MyBatis. Here you will see all the methods of executing statements, committing or rolling back transactions and obtaining mapper instances.

The main methods of executing statements are:

<T> T selectOne(String statement, Object parameter) Query single data  
<E> List<E> selectList(String statement, Object parameter) 
int insert(String statement, Object parameter)  The following needs commit
int update(String statement, Object parameter) 
int delete(String statement, Object parameter)

The main methods of operating transactions are:

void commit()  
void rollback()  

Practice code

mapper:

<?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="userMapper">

<!--    Query operation-->
    <select id="findAll" resultType="user">
         select * from user
    </select>

<!--    Insert operation-->
    <insert id="save" parameterType="com.cheung.domain.User">
        insert into user values (#{id},#{username},#{password})
    </insert>

<!--    Update data-->
    <update id="update" parameterType="com.cheung.domain.User">
        update user set username=#{username},password=#{password} where id=#{id}
    </update>

<!--    Delete operation-->
    <delete id="delete" parameterType="int">
        delete from user where id=#{id}
    </delete>
</mapper>

mybatis core file:

<?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>
<!--    load jdbc configuration file-->
    <properties resource="jdbc.properties"></properties>
    <!--    to User Class defines a typeAliases((alias)-->
    <typeAliases>
        <typeAlias type="com.cheung.domain.User" alias="user"></typeAlias>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="com/cheung/mapper/userMapper.xml"/>
    </mappers>
</configuration>

Test code:

public class MyBatisTest {


    @Test //Delete data
    public void test4() throws IOException {

        //Load core profile
        InputStream resource = Resources.getResourceAsStream("sqlMapConfig.xml");
        //Get sqlSession factory object
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resource);
        //Obtained sqlSession object
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //Execute sql statement to insert data
        int delete = sqlSession.update("userMapper.delete", 0);
        System.out.println(delete);
        //Commit transaction
        sqlSession.commit();
        //Release resources
        sqlSession.close();
    }

    @Test //Update data
    public void test3() throws IOException {

        //Simulate the data transmitted from the web layer to create a User
        User user = new User();
        user.setId(2);
        user.setUsername("zhangxueyou");
        user.setPassword("123");

        //Load core profile
        InputStream resource = Resources.getResourceAsStream("sqlMapConfig.xml");
        //Get sqlSession factory object
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resource);
        //Obtained sqlSession object
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //Execute sql statement to insert data
        int update = sqlSession.update("userMapper.update", user);
        System.out.println(update);
        //Commit transaction
        sqlSession.commit();
        //Release resources
        sqlSession.close();
    }


    @Test //insert
    public void test2() throws IOException {

        //Simulate the data transmitted from the web layer to create a User
        User user = new User();
        user.setUsername("wangwu");
        user.setPassword("456");

        //Load core profile
        InputStream resource = Resources.getResourceAsStream("sqlMapConfig.xml");
        //Get sqlSession factory object
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resource);
        //Obtained sqlSession object
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //Execute sql statement to insert data
        int insert = sqlSession.insert("userMapper.save", user);
        System.out.println(insert);

        //Commit transaction
        sqlSession.commit();
        //Release resources
        sqlSession.close();
    }

    @Test //query
    public void test1() throws IOException {
        //Load core profile
        InputStream resource = Resources.getResourceAsStream("sqlMapConfig.xml");
        //Get sqlSession factory object
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resource);
        //Obtained sqlSession object
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //Execute sql statement to obtain data
        List<User> userList = sqlSession.selectList("userMapper.findAll");
        //sqlSession.selectOne() queries a piece of data
        //print data
        for (User user : userList) {
            System.out.println(user);
        }
        //Release resources
        sqlSession.close();
    }
}

Topics: Java Front-end Spring