Introduction and quick start to Mybatis

Posted by electricshoe on Thu, 27 Jan 2022 12:45:01 +0100

1, Original JDBC

1.1 query data

1.2 insert data

1.3 operation analysis

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

  1. The frequent creation and release of database connections cause a waste of system resources, which affects the system performance
  2. SQL statements are hard coded in the code, which makes the code difficult to maintain. In practical application, SQL changes may be large. SQL changes need to change Java code, which has strong coupling
  3. When querying, you need to manually encapsulate the data in the result set into entities
  4. During the insert operation, you need to manually set the data of the entity to the placeholder position of the SQL statement

Solutions to the above problems:

  1. Initialize connection resources using database connection pool
  2. Extract SQL statements into an XML configuration file
  3. Use reflection, introspection and other underlying technologies to automatically map the fields and attributes of entities and tables

2, Introduction to Mybatis

  • mybatis is an excellent persistence layer framework based on Java, which encapsulates jdbc internally. Developers only need to pay attention to the SQL statement itself, and do not need to spend energy on the complex processes such as loading drivers, creating connections, creating statements, etc
  • mybatis configures various statements to be executed by means of xml or annotation, and generates the final executed SQL statement by mapping Java objects and SQL dynamic parameters 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. JDBC is encapsulated and the underlying access details of jdbc api are shielded, so that we can complete the persistence operation of database without dealing with jdbc api

3, Mybatis quick start

3.1 add mybatis coordinates

3.2 create User data table

3.3 writing User entity classes

3.4 write the mapping file usermapper xml

3.5 write the core file sqlmapconfig xml

3.6 writing test classes

3.6.1 query

UserMapper.xml

<select id="findAll" resultType="com.happy.domain.User"> 
       select * from User    
</select>

Java test code

@Test
//Query operation
 public void test1() throws IOException {
     //Get core profile
     InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
     //Get session factory object
     SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
     //Get session reply object
     SqlSession sqlSession = sqlSessionFactory.openSession();
     //Execution operation parameters: namespace+id
     List<User> userList = sqlSession.selectList("userMapper.findAll");
     //print data
     System.out.println(userList);
     //Release resources
     sqlSession.close();
 }

3.6.2 addition

UserMapper.xml

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

Java test code

@Test
//Insert operation
public void test2() throws IOException {

    //Impersonate user object
    User user = new User();
    user.setUsername("xxx");
    user.setPassword("abc");

    //Get core profile
    InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
    //Get session factory object
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    //Get session reply object
    SqlSession sqlSession = sqlSessionFactory.openSession(true);
    //Execution operation parameters: namespace+id
    sqlSession.insert("userMapper.save",user);

    //mybatis performs the update operation and commits the transaction
    //sqlSession.commit();

    //Release resources
    sqlSession.close();
}

matters needing attention:

  • Insert statements use the insert tag
  • Use the parameterType property 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 changes in database data, so you should use the commit transaction displayed by the sqlSession object, that is, sqlSession commit()

3.6.3 modification

UserMapper.xml

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

Java test code

@Test
//Modify operation
public void test3() throws IOException {

    //Impersonate user object
    User user = new User();
    user.setId(7);
    user.setUsername("lucy");
    user.setPassword("123");

    //Get core profile
    InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
    //Get session factory object
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    //Get session reply object
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //Execution operation parameters: namespace+id
    sqlSession.update("userMapper.update",user);

    //mybatis performs the update operation and commits the transaction
    sqlSession.commit();

    //Release resources
    sqlSession.close();
}

matters needing attention:

  • Modify the statement using the update tag
  • The API used for modification is sqlsession Update ("namespace. id", entity object)

3.6.4 deletion

UserMapper.xml

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

Java test code

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

    //Get core profile
    InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
    //Get session factory object
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    //Get session reply object
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //Execution operation parameters: namespace+id
    sqlSession.delete("userMapper.delete",8);

    //mybatis performs the update operation and commits the transaction
    sqlSession.commit();

    //Release resources
    sqlSession.close();
}

matters needing attention:

  • Delete statements use the delete tag
  • Use #{arbitrary string} to refer to a single parameter passed in a Sql statement
  • The API used for the delete operation is sqlsession Delete ("namespace. id", Object)

3.6.5 query single

UserMapper.xml

<mapper namespace="userMapper">
<!--according to id Make a query-->
    <select id="findById" resultType="com.happy.domain.User" parameterType="int">
        select * from user where id=#{id}
    </select>
</mapper>

Java test code

@Test
//Query an object
public void test5() throws IOException {
    //Get core profile
    InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
    //Get session factory object
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    //Get session reply object
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //Execution operation parameters: namespace+id
    User user = sqlSession.selectOne("userMapper.findById", 1);
    //print data
    System.out.println(user);
    //Release resources
    sqlSession.close();
}

4, Mapper profile overview

UserMapper.xml

5, MyBatis core profile overview

5.1 MyBatis core profile hierarchy

5.2 properties tab

Load the external properties file through the < Properties > tag

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

JDBC under resources Properties file:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root

sqlMapConfig. Reference and use in XML:

<properties resource="jdbc.properties"></properties>
<!--Data source environment-->
<environments default="developement">
    <environment id="developement">
        <transactionManager type="JDBC"></transactionManager>
        <dataSource type="POOLED">
            <property name="driver" value="${jdbc.driver}"/>
            <property name="url" value="${jdbc.url}"/>
            <property name="username" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
        </dataSource>
    </environment>
</environments>

5.3 environment label

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 depends 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 do not 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

5.4 mapper label

The tag is used to load mapping. The loading methods are as follows:

  • Use a resource reference relative to the classpath, for example: < mapper resource = "org / mybatis / builder / AuthorMapper. XML" / >
  • Use a fully qualified resource locator (URL), for example: < mapper URL=“ file:///var/mappers/AuthorMapper.xml "/>
  • Use the mapper interface to implement the fully qualified class name of the class, for example: < mapper class = "org. Mybatis. Builder. AuthorMapper" / >
  • Register all the mapper interface implementations in the package as mappers, for example: < package name = "org. Mybatis. Builder" / >

5.5 typeAliases label

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

<select id="findAll" resultType="com.happy.domain.User">
    select * from User
</select>

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

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

At this point, you can use its alias directly:

<select id="findAll" resultType="user">
    select * from User
</select>

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

6, MyBatis corresponding API

6.1 SqlSession factory builder SqlSessionFactoryBuilder

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 the classpath, the 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 for 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) 
<E> List<E> selectList(String statement, Object parameter) 
int insert(String statement, Object parameter) 
int update(String statement, Object parameter) 
int delete(String statement, Object parameter)

The main methods of operating transactions are:

void commit()  
void rollback() 

Topics: Java Mybatis